List of usage examples for org.springframework.validation BindingResult reject
void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage);
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractTenantController.java
/** * This method used for Editing Tenant Logo * /*from w ww . java2s .c o m*/ * @param tenantParam * @param tenantLogoForm * @param result * @param map * @return String (tenants.editcurrentlogo) */ @RequestMapping(value = "/{tenantParam}/editlogo", method = RequestMethod.POST) public String editTenantLogo(@PathVariable String tenantParam, @ModelAttribute("tenantLogoForm") TenantLogoForm tenantLogoForm, BindingResult result, ModelMap map, HttpServletRequest httpServletRequest) { logger.debug("### edit logo method starting...(POST)"); String fileSize = checkFileUploadMaxSizeException(httpServletRequest); if (fileSize != null) { result.reject("error.image.max.upload.size.exceeded", new Object[] { fileSize }, ""); setPage(map, Page.HOME); return "tenants.editcurrentlogo"; } String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (rootImageDir != null && !rootImageDir.trim().equals("")) { Tenant tenant = tenantService.get(tenantParam); com.citrix.cpbm.access.Tenant proxyTenant = (com.citrix.cpbm.access.Tenant) CustomProxy .newInstance(tenant); String relativeImageDir = tenant.getParam(); TenantLogoFormValidator validator = new TenantLogoFormValidator(); validator.validate(tenantLogoForm, result); if (result.hasErrors()) { setPage(map, Page.HOME); return "tenants.editcurrentlogo"; } else { MultipartFile logoFile = tenantLogoForm.getLogo(); MultipartFile faviconFile = tenantLogoForm.getFavicon(); try { if (StringUtils.isNotEmpty(logoFile.getOriginalFilename())) { String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir, logoFile); proxyTenant.getObject().setImagePath(logoFileRelativePath); } if (StringUtils.isNotEmpty(faviconFile.getOriginalFilename())) { String faviconFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir, faviconFile); proxyTenant.getObject().setFaviconPath(faviconFileRelativePath); } tenantService.update(proxyTenant, result); } catch (IOException e) { logger.debug("###IO Exception in writing custom image file"); } } return "redirect:/portal/home"; } else { result.rejectValue("logo", "error.custom.image.upload.dir"); result.rejectValue("favicon", "error.custom.image.upload.dir"); setPage(map, Page.HOME); return "tenants.editcurrentlogo"; } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java
/** * Method for Phone Verification//from w w w.ja v a 2 s . com * * @param registration * @param result * @param captchaChallenge * @param captchaResponse * @param map * @param channelParam * @param sessionStatus * @param request * @return String */ @RequestMapping(value = "/phone_verification", method = RequestMethod.POST) public String phoneverification(@Valid @ModelAttribute("registration") final UserRegistration registration, BindingResult result, @RequestParam(value = "recaptcha_challenge_field", required = false) String captchaChallenge, @RequestParam(value = "recaptcha_response_field", required = false) String captchaResponse, final ModelMap map, @ModelAttribute("channelParam") final String channelParam, SessionStatus sessionStatus, HttpServletRequest request) { if (!Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) { try { verifyCaptcha(captchaChallenge, captchaResponse, getRemoteUserIp(request), captchaService); } catch (CaptchaFailureException ex) { IPtoCountry iPtoCountry = super.getGeoIpToCountry(request); List<Country> filteredCountryList = getFilteredCountryList(registration.getCountryList()); map.addAttribute("filteredCountryList", filteredCountryList); if (registration.getUser().getAddress().getCountry().length() > 0) { map.addAttribute("ipToCountryCode", registration.getUser().getAddress().getCountry()); } else { map.addAttribute("ipToCountryCode", iPtoCountry.getCountryCode()); } map.addAttribute("registrationError", "captcha.error"); map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey()); map.addAttribute("allowSecondaryCheckBox", registration.getTenant().getAccountType().isEnableSecondaryAddress()); result.reject("errors.registration.captcha", null, null); map.addAttribute("showCaptcha", true); return "register.moreuserinfo"; } } else { logger.debug("No captcha verification required because intranet only mode is enabled"); } Country country = countryService.locateCountryByCode(registration.getUser().getAddress().getCountry()); registration.setCountryName(country.getName()); registration.setCountryCode(country.getIsdCode()); Random rnd = new Random(); int n = 99999 - 1000; request.getSession().setAttribute("phoneVerificationPin", "" + rnd.nextInt(n)); map.addAttribute("registration", registration); return "register.phoneverification"; }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java
/** * This method is used for Register.// www .j a v a2 s. c o m * * @param registration * @param result * @param captchaChallenge * @param captchaResponse * @param map * @param channelParam * @param sessionStatus * @param request * @return String */ @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(@Valid @ModelAttribute("registration") final UserRegistration registration, final BindingResult result, @RequestParam(value = "recaptcha_challenge_field", required = false) String captchaChallenge, @RequestParam(value = "recaptcha_response_field", required = false) String captchaResponse, final ModelMap map, @ModelAttribute("channelParam") final String channelParam, SessionStatus sessionStatus, HttpServletRequest request) { logger.debug("###Entering in register( method @POST"); map.addAttribute("page", Page.HOME); map.addAttribute("registration", registration); addFraudProfilingHostToSession(map); IPtoCountry iPtoCountry = super.getGeoIpToCountry(request); List<Country> filteredCountryList = getFilteredCountryList(registration.getCountryList()); map.addAttribute("filteredCountryList", filteredCountryList); if (registration.getUser().getAddress().getCountry().length() > 0) { map.addAttribute("ipToCountryCode", registration.getUser().getAddress().getCountry()); } else { map.addAttribute("ipToCountryCode", iPtoCountry.getCountryCode()); } map.addAttribute(Page.HOME.getLevel1().name(), "on"); map.addAttribute("allowSecondaryCheckBox", registration.getTenant().getAccountType().isEnableSecondaryAddress()); if (!registration.getPhoneVerificationEnabled() && !Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) { try { verifyCaptcha(captchaChallenge, captchaResponse, getRemoteUserIp(request), captchaService); } catch (CaptchaFailureException ex) { map.addAttribute("registrationError", "captcha.error"); map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey()); map.addAttribute("showCaptcha", true); result.reject("errors.registration.captcha", null, null); map.addAttribute("allowSecondaryCheckBox", registration.getTenant().getAccountType().isEnableSecondaryAddress()); return "register.moreuserinfo"; } } registration.getUser().setPhone(registration.getUser().getPhone().replaceAll(PHONE_NUMBER_REGEX, "")); TelephoneVerificationService telephoneVerificationService = (TelephoneVerificationService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION); if (telephoneVerificationService != null && telephoneVerificationService.isEnabled()) { String generatedPhoneVerificationPin = request.getSession().getAttribute("phoneVerificationPin") .toString(); String actualPhoneNumber = request.getSession().getAttribute("phoneNumber").toString(); if (!registration.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin) || !areDigitsInPhoneNosEqual(registration.getUser().getPhone(), actualPhoneNumber)) { map.addAttribute("registrationError", "phoneVerfication.error"); result.reject("errors.registration.user.phone", null, null); return "register.phoneverification"; } } if (result.hasErrors()) { displayErrors(result); parseResult(result, map); return "register.userinfo"; } // Device intelligence and fraud detection ReviewStatus fraudStatus = null; DeviceFraudDetectionAudit log = null; DeviceFraudDetectionService deviceFraudDetectionService = (DeviceFraudDetectionService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.DEVICE_FRAUD_CONTROL); if (deviceFraudDetectionService != null && deviceFraudDetectionService.isEnabled()) { fraudStatus = assessAccountCreationRisk(registration, request); if (fraudStatus == ReviewStatus.FAIL) { return "register.fail"; } log = ((DeviceFraudDetectionService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.DEVICE_FRAUD_CONTROL)) .getLastLog(request.getSession().getId(), registration.getUser().getUsername()); String message = "device.fraud"; Tenant tenant = tenantService.getSystemTenant(); String messageArguments = registration.getUser().getUsername(); Event event = null; switch (fraudStatus) { case REJECT: context.publishEvent(new PortalEvent("Device Fraud Detection Event", actorService.getActor(), new DeviceFraudDetectionEvent(log, registration.getUser().getUsername(), registration.getUser().getEmail(), registration.getUser().getPhone(), registration.getUser().getFirstName(), registration.getUser().getLastName()))); event = new Event(new Date(), message, messageArguments, tenant, Source.PORTAL, Scope.ACCOUNT, Category.ACCOUNT, Severity.CRITICAL, true); eventService.createEvent(event, false); return "register.fail"; case REVIEW: // account to be manual activated registration.getTenant().setIsManualActivation(true); context.publishEvent(new PortalEvent("Device Fraud Detection Event", actorService.getActor(), new DeviceFraudDetectionEvent(log, registration.getUser().getUsername(), registration.getUser().getEmail(), registration.getUser().getPhone(), registration.getUser().getFirstName(), registration.getUser().getLastName()))); event = new Event(new Date(), message, messageArguments, tenant, Source.PORTAL, Scope.ACCOUNT, Category.ACCOUNT, Severity.ALERT, true); eventService.createEvent(event, false); // Model should know fraud has been detected map.put("deviceFraudDetected", true); default: break; } } // This checks whether the trial code is valid or not map.addAttribute("supportEmail", config.getValue(Names.com_citrix_cpbm_portal_addressbook_helpDeskEmail)); map.addAttribute("supportPhone", config.getValue(Names.com_citrix_cpbm_portal_settings_helpdesk_phone)); // post processing for trial code if (!StringUtils.isEmpty(registration.getTrialCode())) { String promoCode = registration.getTrialCode(); String channelCode = channelService.getChannel(channelParam).getCode(); if (!promotionService.isValidPromotion(promoCode, channelCode)) { logger.debug("Invalid promo code " + promoCode + " for channel code " + channelCode); return "register.fail"; } // preempt trial account type creation if NOT supported [TA10428] CampaignPromotion cp = promotionService.locatePromotionByToken(promoCode); AccountType requestedAccountType = registrationService .getAccountTypeById(registration.getAccountTypeId()); if (requestedAccountType.equals(registrationService.getTrialAccountType()) && !cp.isTrial()) { logger.debug("Invalid promo code " + promoCode + " for account type " + requestedAccountType); return "register.fail"; } } registration.getTenant().setAddress(registration.getUser().getAddress()); if (!registration.isAllowSecondary()) { registration.getTenant().setSecondaryAddress(null); } else { registration.getTenant().setSecondaryAddress(registration.getSecondaryAddress()); } registration.getTenant().setSyncBillingAddress(true); // to store error messages List<String> errorMsgList = new ArrayList<String>(); try { final com.citrix.cpbm.access.User owner = registration.getUser(); if (registration.getCountryCode() == null || registration.getCountryCode().equals("")) { Country country = countryService .locateCountryByCode(registration.getUser().getAddress().getCountry()); registration.setCountryName(country.getName()); registration.setCountryCode(country.getIsdCode()); } String phoneNo = registration.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "") + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + owner.getPhone().replaceAll(PHONE_NUMBER_REGEX, ""); // Set the phone number owner.setPhone(phoneNo); owner.setLocale(registration.getUser().getLocale()); registration.getTenant().setRemoteAddress(getRemoteUserIp(request)); // set currency for (CurrencyValue cv : registration.getCurrencyValueList()) { if (cv.getCurrencyCode().equals(registration.getCurrency())) { registration.getTenant().setCurrency(cv); break; } } privilegeService.runAsPortal(new PrivilegedAction<Void>() { @Override public Void run() { AccountType requestedAccountType = registrationService .getAccountTypeById(registration.getAccountTypeId()); if (requestedAccountType.equals(registrationService.getTrialAccountType())) { TrialAccount account = null; try { account = registrationService.registerTrialAccount(registration.getTrialCode(), registration.getTenant(), owner, channelParam); } catch (TrialCodeInvalidException e) { logger.debug("Invalid Trial Code", e); } catch (ConnectorManagementServiceException e) { logger.debug("Cannot find service instance", e); } map.addAttribute("trial", account); return null; } else { try { registrationService.registerTenant(registration.getTenant(), owner, channelParam, registration.getTrialCode(), result); } catch (ConnectorManagementServiceException e) { logger.debug("Cannot find service instance", e); } } if (!result.hasErrors()) { Tenant t = tenantService.get(registration.getTenant().getUuid()); t.setAccountType(registrationService.getAccountTypeById(registration.getAccountTypeId())); t.getTenantExtraInformation() .setPaymentMode(requestedAccountType.getSupportedPaymentModes().get(0)); tenantService.save(t); registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(t)); } return null; } }); if (deviceFraudDetectionService != null && deviceFraudDetectionService.isEnabled()) { log.setUserId(registration.getTenant().getOwner().getId()); } map.addAttribute("tenant", registration.getTenant()); String homeUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_home_url); String cloudmktgUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_marketing_url); if (homeUrl != null) { map.addAttribute("homeUrl", homeUrl); } if (cloudmktgUrl != null) { map.addAttribute("cloudmktgUrl", cloudmktgUrl); } } catch (DataAccessException ex) { logger.error(ex); result.reject("errors.registration", new Object[] { ex.getMessage() }, null); errorMsgList.add("You must accept the terms and conditions to use this service"); } catch (TrialCodeInvalidException ex) { result.rejectValue("trialCode", "errors.registration.invalid_trial_code", null); map.addAttribute("trialCode", "errors.registration.invalid_trial_code"); logger.debug("registrationError " + ex.getMessage()); } catch (TrialMaxAccountReachedException ex) { result.rejectValue("trialCode", "errors.registration.max_trial_reached", null); map.addAttribute("trialCode", "errors.registration.max_trial_reached"); logger.debug("registrationError " + ex.getMessage()); } catch (Exception ex) { logger.error("registrationError ", ex); return "redirect:/portal/errors/error"; } if (result.hasErrors()) { displayErrors(result); parseResult(result, map); registration.reset(); registration.setCurrency(config.getValue(Names.com_citrix_cpbm_portal_settings_default_currency)); if (errorMsgList.size() > 0) { map.addAttribute("errorMsgList", errorMsgList); map.addAttribute("errormsg", true); } logger.debug("###Exiting register(registration,result,captchaChallenge,,captchaResponse," + "map,sessionStatus,request) method @POST"); map.addAttribute("allowSecondaryCheckBox", registration.getTenant().getAccountType().isEnableSecondaryAddress()); if (!Boolean.valueOf(config.getValue(Names.com_citrix_cpbm_use_intranet_only))) { map.addAttribute("recaptchaPublicKey", config.getRecaptchaPublicKey()); map.addAttribute("showCaptcha", true); } return "register.moreuserinfo"; } else { sessionStatus.setComplete(); // clean up parameters in session. logger.debug("###Exiting register(registration,result,captchaChallenge,,captchaResponse," + "map,sessionStatus,request) method @POST"); map.addAttribute("user", registration.getUser()); return "register.registration_success"; } }
From source file:de.interactive_instruments.etf.webapp.controller.TestObjectController.java
@RequestMapping(value = "/testobjects/add-file-to", method = RequestMethod.POST) public String addFileTestData(@ModelAttribute("testObject") @Valid TestObjectDto testObject, BindingResult result, MultipartHttpServletRequest request, Model model) throws IOException, URISyntaxException, StoreException, ParseException, NoSuchAlgorithmException { if (SUtils.isNullOrEmpty(testObject.getLabel())) { throw new IllegalArgumentException("Label is empty"); }/* w w w . j a va 2 s.co m*/ if (result.hasErrors()) { return showCreateDoc(model, testObject); } final GmlAndXmlFilter filter; final String regex = testObject.getProperty("regex"); if (regex != null && !regex.isEmpty()) { filter = new GmlAndXmlFilter(new RegexFileFilter(regex)); } else { filter = new GmlAndXmlFilter(); } // Transfer uploaded data final MultipartFile multipartFile = request.getFile("testObjFile"); if (multipartFile != null && !multipartFile.isEmpty()) { // Transfer file to tmpUploadDir final IFile testObjFile = this.tmpUploadDir .secureExpandPathDown(testObject.getLabel() + "_" + multipartFile.getOriginalFilename()); testObjFile.expectFileIsWritable(); multipartFile.transferTo(testObjFile); final String type; try { type = MimeTypeUtils.detectMimeType(testObjFile); if (!type.equals("application/xml") && !type.equals("application/zip")) { throw new IllegalArgumentException(type + " is not supported"); } } catch (Exception e) { result.reject("l.upload.invalid", new Object[] { e.getMessage() }, "Unable to use file: {0}"); return showCreateDoc(model, testObject); } // Create directory for test data file final IFile testObjectDir = testDataDir .secureExpandPathDown(testObject.getLabel() + ".upl." + getSimpleRandomNumber(4)); testObjectDir.ensureDir(); if (type.equals("application/zip")) { // Unzip files to test directory try { testObjFile.unzipTo(testObjectDir, filter); } catch (IOException e) { try { testObjectDir.delete(); } catch (Exception de) { ExcUtils.supress(de); } result.reject("l.decompress.failed", new Object[] { e.getMessage() }, "Unable to decompress file: {0}"); return showCreateDoc(model, testObject); } finally { // delete zip file testObjFile.delete(); } } else { // Move XML to test directory testObjFile.copyTo(testObjectDir.getPath() + File.separator + multipartFile.getOriginalFilename()); } testObject.addResource("data", testObjectDir.toURI()); testObject.getProperties().setProperty("uploaded", "true"); } else { final URI resURI = testObject.getResourceById("data"); if (resURI == null) { throw new StoreException("Workflow error. Data path resource not set."); } final IFile absoluteTestObjectDir = testDataDir.secureExpandPathDown(resURI.getPath()); testObject.getResources().clear(); testObject.getResources().put(EidFactory.getDefault().createFromStrAsStr("data"), absoluteTestObjectDir.toURI()); // Check if file exists final IFile sourceDir = new IFile(new File(testObject.getResourceById("data"))); try { sourceDir.expectDirIsReadable(); } catch (Exception e) { result.reject("l.testObject.testdir.insufficient.rights", new Object[] { e.getMessage() }, "Insufficient rights to read directory: {0}"); return showCreateDoc(model, testObject); } testObject.getProperties().setProperty("uploaded", "false"); } final FileHashVisitor v = new FileHashVisitor(filter); Files.walkFileTree(new File(testObject.getResourceById("data")).toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), 5, v); if (v.getFileCount() == 0) { if (regex != null && !regex.isEmpty()) { result.reject("l.testObject.regex.null.selection", new Object[] { regex }, "No files were selected with the regular expression \"{0}\"!"); } else { result.reject("l.testObject.testdir.no.xml.gml.found", "No file were found in the directory with a gml or xml file extension"); } return showCreateDoc(model, testObject); } VersionDataDto vd = new VersionDataDto(); vd.setItemHash(v.getHash()); testObject.getProperties().setProperty("files", String.valueOf(v.getFileCount())); testObject.getProperties().setProperty("size", String.valueOf(v.getSize())); testObject.getProperties().setProperty("sizeHR", FileUtils.byteCountToDisplaySize(v.getSize())); testObject.setVersionData(vd); testObject.setId(EidFactory.getDefault().createRandomUuid()); testObjStore.create(testObject); return "redirect:/testobjects"; }
From source file:easycare.web.user.UserController.java
private boolean isUserValidForCreation(final NewUserForm newUserForm, final BindingResult result) { // Check Username is unique final String username = newUserForm.getUsername(); if (userService.findByUsernameWithContactInformation(username) != null) { result.reject(USER_NAME_ALREADY_EXISTS, new Object[] { username }, null); fireCreateUserFailedDuplicateUsernameEvent(newUserForm); return false; }//from w ww . j a v a 2s. c o m // Check email is unique final String email = newUserForm.getEmail(); if (email != null && userService.findByEmail(email) != null) { result.reject(EMAIL_ALREADY_EXISTS, new Object[] { email }, null); fireCreateUserFailedDuplicateEmailEvent(newUserForm); return false; } return true; }
From source file:org.bibsonomy.webapp.view.CSVView.java
@Override protected void renderMergedOutputModel(final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception { /*/*from w w w . j a v a 2s . c o m*/ * get the data */ final Object object = model.get(BaseCommandController.DEFAULT_COMMAND_NAME); if (object instanceof SimpleResourceViewCommand) { /* * we can only handle SimpleResourceViewCommands ... */ final SimpleResourceViewCommand command = (SimpleResourceViewCommand) object; /* * set the content type headers */ response.setContentType("text/csv"); response.setCharacterEncoding("UTF-8"); /* * get the requested path * we need it to generate the file names for inline content-disposition * FIXME: The path is written into the request by the UrlRewriteFilter * ... probably this is not a good idea */ // final String requPath = (String) request.getAttribute("requPath"); // response.setHeader("Content-Disposition", "attachement; filename=" + Functions.makeCleanFileName(requPath) + extension); try { /* * write the buffer to the response */ final ServletOutputStream outputStream = response.getOutputStream(); final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(outputStream, "UTF-8")); /* * write header */ csvWriter.writeNext(new String[] { "intrahash", "user", "date", "tags", "groups", "description", "title", // publication-only fields "bibtexKey", // from here: sorted by alphabet "address", "annote", "author", "entrytype", "booktitle", "chapter", "crossref", "day", "edition", "editor", "howpublished", "institution", "journal", "key", "month", "note", "number", "organization", "pages", "publisher", "school", "series", "type", "volume", "year", // remaining "special" fields "private note", "misc", "abstract" }); /* * write publications */ final List<Post<BibTex>> publicationList = command.getBibtex().getList(); if (publicationList != null) { for (final Post<BibTex> post : publicationList) { final BibTex resource = post.getResource(); csvWriter.writeNext(getArray(post, resource.getAuthor(), resource.getEditor(), resource.getBibtexKey(), resource.getAnnote(), resource.getBooktitle(), resource.getCrossref(), resource.getAddress(), resource.getEntrytype(), resource.getChapter(), resource.getEdition(), resource.getDay(), resource.getHowpublished(), resource.getInstitution(), resource.getJournal(), resource.getMonth(), resource.getKey(), resource.getNumber(), resource.getOrganization(), resource.getNote(), resource.getPages(), resource.getPublisher(), resource.getSchool(), resource.getSeries(), resource.getType(), resource.getVolume(), resource.getYear(), resource.getPrivnote(), resource.getMisc(), resource.getAbstract())); } } /* * write bookmarks */ final List<Post<Bookmark>> bookmarkList = command.getBookmark().getList(); if (bookmarkList != null) { for (final Post<Bookmark> post : bookmarkList) { csvWriter.writeNext(getArray(post, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null)); } } csvWriter.close(); } catch (final IOException e) { log.error("Could not render CSV view.", e); /* * layout could not be found or contains errors -> set HTTP status to 400 */ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); /* * get the errors object and add the error message */ final BindingResult errors = ViewUtils.getBindingResult(model); errors.reject("error.layout.rendering", new Object[] { e.getMessage() }, "Could not render layout: " + e.getMessage()); /* * do the rendering ... a bit tricky: we need to get an appropriate JSTL view and give it the * application context */ final JstlView view = new JstlView("/WEB-INF/jsp/error.jspx"); view.setApplicationContext(getApplicationContext()); view.render(model, request, response); } } else { /* * FIXME: what todo here? */ } }
From source file:org.bibsonomy.webapp.view.LayoutView.java
@Override protected void renderMergedOutputModel(final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception { /*//from w w w.j a v a 2s. c om * get the data */ final Object object = model.get(BaseCommandController.DEFAULT_COMMAND_NAME); if (object instanceof SimpleResourceViewCommand) { /* * we can only handle SimpleResourceViewCommands ... */ final SimpleResourceViewCommand command = (SimpleResourceViewCommand) object; final String loginUserName = command.getContext().getLoginUser().getName(); /* * get requested layout */ final String layout = command.getLayout(); final boolean formatEmbedded = command.getformatEmbedded(); /* * get the requested path * we need it to generate the file names for inline content-disposition * FIXME: The path is written into the request by the UrlRewriteFilter * ... probably this is not a good idea */ final String requPath = (String) request.getAttribute("requPath"); log.info("rendering layout " + layout + " for user " + loginUserName + " with path " + requPath); /* * */ final List<Post<BibTex>> publicationPosts = command.getBibtex().getList(); try { /* * our basic (and only) renderer is the jabref layout renderer, which supports * only publications */ if (layoutRenderer.supportsResourceType(BibTex.class)) { /* * render publication posts */ renderResponse(layout, requPath, publicationPosts, loginUserName, response, formatEmbedded); } else { /* * we could not find a suitable renderer - this should never happen! */ throw new RuntimeException("No layout for publications renderer available."); } } catch (final LayoutRenderingException e) { log.error("Could not render layout " + layout + ": " + e.getMessage()); /* * layout could not be found or contains errors -> set HTTP status to 400 */ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); /* * get the errors object and add the error message */ final BindingResult errors = ViewUtils.getBindingResult(model); errors.reject("error.layout.rendering", new Object[] { e.getMessage() }, "Could not render layout: " + e.getMessage()); /* * do the rendering ... a bit tricky: we need to get an appropriate JSTL view and give it the * application context */ final JstlView view = new JstlView("/WEB-INF/jsp/error.jspx"); view.setApplicationContext(getApplicationContext()); view.render(model, request, response); } } else { /* * FIXME: what todo here? */ } }