private PdfPTable footer() {

    PdfPTable footer = new PdfPTable(1);
    footer.setTotalWidth(523);
    Font colorLetra = new Font();
    colorLetra.setColor(new BaseColor(Color.white));
    colorLetra.setSize(8);

    PdfPCell cell =
        new PdfPCell(
            new Paragraph(
                messageSource.getMessage("generaPdf.pdf.DireccionPart1", null, Locale.getDefault()),
                colorLetra));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(new BaseColor(0, 0, 0));
    footer.addCell(cell);
    cell =
        new PdfPCell(
            new Paragraph(
                messageSource.getMessage("generaPdf.pdf.DireccionPart2", null, Locale.getDefault()),
                colorLetra));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(new BaseColor(0, 0, 0));
    footer.addCell(cell);
    cell =
        new PdfPCell(
            new Paragraph(
                messageSource.getMessage("generaPdf.pdf.DireccionPart3", null, Locale.getDefault()),
                colorLetra));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(new BaseColor(0, 0, 0));
    footer.addCell(cell);
    return footer;
  }
示例#2
0
  public String addItemWithAjax() {

    Book book = bookManager.getBookByIsbn(bookId);

    if (loggedCustomer != null && theCart != null) {
      if (book != null) {
        theCart.addItem(book.getIsbn());
        String message =
            ajaxContentProvider.getCartUpdateAsJson(
                "ok", book.getTitle(), theCart.getCount(), null);
        inputStream = new ByteArrayInputStream(message.getBytes());
        return ActionSupport.SUCCESS;
      } else {
        error =
            ajaxContentProvider.getCartUpdateAsJson(
                "ko",
                null,
                null,
                messageProvider.getMessage(
                    "web.error.book.unknown", new Object[] {bookId}, null, null));
        inputStream = new ByteArrayInputStream(error.getBytes());
        return ActionSupport.ERROR;
      }
    } else {
      error =
          ajaxContentProvider.getCartUpdateAsJson(
              "ko",
              null,
              null,
              messageProvider.getMessage("web.error.purchase.login", null, null, null));
      inputStream = new ByteArrayInputStream(error.getBytes());
      return ActionSupport.ERROR;
    }
  }
 public static void main(String args[]) throws Exception {
   ApplicationContext ctx = new ClassPathXmlApplicationContext("message.xml");
   MessageSource messageSource = (MessageSource) ctx.getBean("messageSource");
   Locale locale = new Locale("en", "US");
   String msg = messageSource.getMessage("welcome.message", new Object[] {"Hi", "Majrul"}, locale);
   System.out.println(msg);
 }
示例#4
0
 @RequestMapping(method = RequestMethod.POST)
 public String create(
     @Valid Banks banks,
     BindingResult bindingResult,
     Model uiModel,
     HttpServletRequest httpServletRequest,
     RedirectAttributes redirectAttributes,
     Locale locale) {
   logger.info("Creating banks");
   if (bindingResult.hasErrors()) {
     uiModel.addAttribute(
         "message",
         new Message(
             "error", messageSource.getMessage("banks_save_fail", new Object[] {}, locale)));
     uiModel.addAttribute("banks", banks);
     return "banks/create";
   }
   uiModel.asMap().clear();
   redirectAttributes.addFlashAttribute(
       "message",
       new Message(
           "success", messageSource.getMessage("banks_save_success", new Object[] {}, locale)));
   logger.info("Banks id: " + banks.getId());
   banksService.save(banks);
   return "redirect:/banks/";
 }
示例#5
0
 @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
 public String update(
     @Valid Banks banks,
     BindingResult bindingResult,
     Model uiModel,
     HttpServletRequest httpServletRequest,
     RedirectAttributes redirectAttributes,
     Locale locale) {
   logger.info("Updating banks");
   if (bindingResult.hasErrors()) {
     uiModel.addAttribute(
         "message",
         new Message(
             "error", messageSource.getMessage("banks_save_fail", new Object[] {}, locale)));
     uiModel.addAttribute("banks", banks);
     return "banks/update";
   }
   logger.info(banks.getName());
   uiModel.asMap().clear();
   redirectAttributes.addFlashAttribute(
       "message",
       new Message(
           "success", messageSource.getMessage("banks_save_success", new Object[] {}, locale)));
   banksService.save(banks);
   return "redirect:/banks/"
       + UrlUtil.encodeUrlPathSegment(banks.getId().toString(), httpServletRequest);
 }
  @RequestMapping(value = "/waiter/bills/{billId}", method = RequestMethod.GET)
  public String showBillInWaiter(
      @PathVariable("billId") String billId, Model uiModel, Locale locale) {

    // warmup stuff
    Bill bill = warmupRestaurant(billId, uiModel);
    Restaurant resto = bill.getDiningTable().getRestaurant();

    List<Order> allPreparedOrders = orderService.findPreparedOrdersForRestaurant(resto);
    uiModel.addAttribute("allPreparedOrders", allPreparedOrders);

    List<Bill> allSubmittedBills = billService.findSubmittedBillsForRestaurant(resto);
    uiModel.addAttribute("allSubmittedBills", allSubmittedBills);

    uiModel.addAttribute(
        "message",
        new Message(
            "info",
            messageSource.getMessage("label_bill_amount", new Object[] {}, locale)
                + ": "
                + bill.getPriceAllOrders()
                + " "
                + messageSource.getMessage("label_currency", new Object[] {}, locale)));

    return "hartigehap/waiter";
  }
  @RequestMapping(params = "addNode", method = RequestMethod.POST)
  public String addNode(
      @ModelAttribute("newNode") @Valid Node newNode,
      BindingResult bindingResult,
      Model uiModel,
      RedirectAttributes redirectAttributes,
      Locale locale) {
    validateNode(newNode.getName(), newNode.getAddress(), bindingResult);
    if (bindingResult.hasErrors()) {
      uiModel.addAttribute(
          "message",
          new Message(
              "error",
              messageSource.getMessage("label_node_add_failure", new Object[] {}, locale)));
      uiModel.addAttribute("newNode", newNode);
      return "nodes/list";
    }
    // uiModel.asMap().clear();
    // redirectAttributes.addFlashAttribute("message")

    uiModel.addAttribute(
        "message",
        new Message(
            "success",
            messageSource.getMessage("label_node_add_success", new Object[] {}, locale)));
    nodeService.save(newNode);
    uiModel.addAttribute("newNode", new Node());

    return "nodes/list";
  }
示例#8
0
  // create new category, save to database
  @RequestMapping(params = "form", method = RequestMethod.POST)
  public String create(
      @Valid Category category,
      BindingResult bindingResult,
      Model uiModel,
      HttpServletRequest httpServletRequest,
      RedirectAttributes redirectAttributes,
      Locale locale) {
    logger.info("Creating category");
    if (bindingResult.hasErrors()) {
      uiModel.addAttribute(
          "message",
          new Message(
              "error", messageSource.getMessage("category_save_fail", new Object[] {}, locale)));
      uiModel.addAttribute("category", category);
      addCategoryHomeLink(uiModel);
      resetCategories(uiModel, category, categoryService.findParents());
      return "categories/create";
    }

    uiModel.asMap().clear();
    redirectAttributes.addFlashAttribute(
        "message",
        new Message(
            "success", messageSource.getMessage("category_save_success", new Object[] {}, locale)));
    String parentCategoryId = category.getParentCategoryId();
    if (parentCategoryId != null && !parentCategoryId.equals(""))
      category.setParentCategory(categoryService.findById(Integer.valueOf(parentCategoryId)));

    categoryService.save(category);
    return "redirect:/admin/categories/"
        + UrlUtil.encodeUrlPathSegment(category.getCategoryId().toString(), httpServletRequest)
        + "?form";
  }
  /** Get customer for a customerId and merchantId */
  @WebMethod
  public @WebResult GetCustomerWebServiceResponse getCustomer(
      @WebParam(name = "credentials") WebServiceCredentials credentials,
      @WebParam(name = "customer") Customer customer) {
    MessageSource messageSource = (MessageSource) SpringUtil.getBean("messageSource");

    Locale locale = LocaleUtil.getDefaultLocale();
    if (StringUtils.isNotBlank(customer.getCustomerLang())) {
      locale = LocaleUtil.getLocale(customer.getCustomerLang());
    }

    GetCustomerWebServiceResponse response = new GetCustomerWebServiceResponse();
    try {

      if (customer.getCustomerId() == 0) {
        setStatusMsg(messageSource, locale, response, "messages.authorization", 0);
        return response;
      }
      // check credentials
      validateCredentials(locale, credentials);

      CustomerService cservice =
          (CustomerService) ServiceFactory.getService(ServiceFactory.CustomerService);
      com.salesmanager.core.entity.customer.Customer entityCustomer =
          cservice.getCustomer(customer.getCustomerId());
      if (entityCustomer == null) {
        setStatusMsg(messageSource, locale, response, "messages.customer.doesnotexist", 0);
        return response;
      }

      if (entityCustomer.getMerchantId() != credentials.getMerchantId()) {
        setStatusMsg(messageSource, locale, response, "messages.authorization", 0);
        return response;
      }

      Customer webCustomer = new Customer();
      BeanUtils.copyProperties(webCustomer, entityCustomer);
      response.setCustomer(webCustomer);
      response.setStatus(1);

    } catch (Exception e) {

      if (e instanceof ServiceException) {
        String[] msg = {((ServiceException) e).getMessage()};
        response.setMessages(msg);
        response.setStatus(0);
      } else {

        log.error("Exception occurred while creating Customer", e);
        response.setMessages(
            new String[] {messageSource.getMessage("errors.technical", null, locale)});
        response.setStatus(0);
      }
    }
    return response;
  }
  @ModelAttribute("gender")
  public Map<String, String> getGender(HttpSession session) {
    Locale locale =
        (Locale) session.getAttribute(SessionLocaleResolver.class.getName() + ".LOCALE");

    Map<String, String> map = new HashMap<String, String>();
    map.put("male", messageSource.getMessage("member.regist.gender.male", null, locale));
    map.put("female", messageSource.getMessage("member.regist.gender.female", null, locale));
    return map;
  }
 @Override
 public BackupResourceProviderInfo providerInfo(Locale locale) {
   String name = "Settings Backup Provider";
   String desc = "Backs up system settings.";
   MessageSource ms = messageSource;
   if (ms != null) {
     name = ms.getMessage("title", null, name, locale);
     desc = ms.getMessage("desc", null, desc, locale);
   }
   return new SimpleBackupResourceProviderInfo(getKey(), name, desc);
 }
  @Test
  public void testBeanNameAutoProxyCreator() {
    StaticApplicationContext sac = new StaticApplicationContext();
    sac.registerSingleton("testInterceptor", TestInterceptor.class);

    RootBeanDefinition proxyCreator = new RootBeanDefinition(BeanNameAutoProxyCreator.class);
    proxyCreator.getPropertyValues().add("interceptorNames", "testInterceptor");
    proxyCreator
        .getPropertyValues()
        .add("beanNames", "singletonToBeProxied,innerBean,singletonFactoryToBeProxied");
    sac.getDefaultListableBeanFactory()
        .registerBeanDefinition("beanNameAutoProxyCreator", proxyCreator);

    RootBeanDefinition bd =
        new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
    RootBeanDefinition innerBean = new RootBeanDefinition(TestBean.class);
    bd.getPropertyValues().add("spouse", new BeanDefinitionHolder(innerBean, "innerBean"));
    sac.getDefaultListableBeanFactory().registerBeanDefinition("singletonToBeProxied", bd);

    sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class);
    sac.registerSingleton("autowiredIndexedTestBean", IndexedTestBean.class);

    sac.refresh();

    MessageSource messageSource = (MessageSource) sac.getBean("messageSource");
    ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied");
    assertFalse(Proxy.isProxyClass(messageSource.getClass()));
    assertTrue(Proxy.isProxyClass(singletonToBeProxied.getClass()));
    assertTrue(Proxy.isProxyClass(singletonToBeProxied.getSpouse().getClass()));

    // test whether autowiring succeeded with auto proxy creation
    assertEquals(
        sac.getBean("autowiredIndexedTestBean"), singletonToBeProxied.getNestedIndexedBean());

    TestInterceptor ti = (TestInterceptor) sac.getBean("testInterceptor");
    // already 2: getSpouse + getNestedIndexedBean calls above
    assertEquals(2, ti.nrOfInvocations);
    singletonToBeProxied.getName();
    singletonToBeProxied.getSpouse().getName();
    assertEquals(5, ti.nrOfInvocations);

    ITestBean tb = (ITestBean) sac.getBean("singletonFactoryToBeProxied");
    assertTrue(AopUtils.isJdkDynamicProxy(tb));
    assertEquals(5, ti.nrOfInvocations);
    tb.getAge();
    assertEquals(6, ti.nrOfInvocations);

    ITestBean tb2 = (ITestBean) sac.getBean("singletonFactoryToBeProxied");
    assertSame(tb, tb2);
    assertEquals(6, ti.nrOfInvocations);
    tb2.getAge();
    assertEquals(7, ti.nrOfInvocations);
  }
示例#13
0
 public String getErrorMessage(MessageSource messageSource, Locale locale) {
   try {
     String errorName = "validation." + Math.abs(errorCode);
     return messageSource.getMessage(errorName, null, locale)
         + " (Error Code : "
         + errorCode
         + ")";
   } catch (Exception ex) {
     return messageSource.getMessage("error.unknown", null, locale)
         + " (Error Code : "
         + errorCode
         + ")";
   }
 }
  private void validateAddressesCache() {
    senderCache.clear();

    if (messageSource == null || serverDescriptor == null) {
      return;
    }

    for (Language language : Language.values()) {
      for (Sender sender : Sender.values()) {
        try {
          final String address =
              messageSource.getMessage(
                  "mail.address." + sender.getCode(),
                  null,
                  sender.getCode() + "@" + serverDescriptor.getMailHostName(),
                  language.getLocale());

          final String personal =
              messageSource.getMessage(
                  "mail.personal." + sender.getCode(), null, sender.name(), language.getLocale());

          senderCache.put(
              new SenderKey(sender, language), new InternetAddress(address, personal, "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
          log.error("JAVA SYSTEM ERROR - NOT UTF8!", ex);
        }
      }

      for (Recipient.MailBox mailBox : Recipient.MailBox.values()) {
        try {
          final String address =
              messageSource.getMessage(
                  "mail.address." + mailBox.getCode(),
                  null,
                  mailBox.getCode() + "@" + serverDescriptor.getMailHostName(),
                  language.getLocale());

          final String personal =
              messageSource.getMessage(
                  "mail.personal." + mailBox.getCode(), null, mailBox.name(), language.getLocale());

          recipientCache.put(
              new RecipientKey(mailBox, language), new InternetAddress(address, personal, "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
          log.error("JAVA SYSTEM ERROR - NOT UTF8!", ex);
        }
      }
    }
  }
示例#15
0
 @RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
 public String confirmRegistration(
     final Locale locale, final Model model, @RequestParam("token") final String token) {
   final String result = userService.validateVerificationToken(token);
   if (result == null) {
     model.addAttribute("message", messages.getMessage("message.accountVerified", null, locale));
     return "redirect:/login?lang=" + locale.getLanguage();
   }
   if (result == "expired") {
     model.addAttribute("expired", true);
     model.addAttribute("token", token);
   }
   model.addAttribute("message", messages.getMessage("auth.message." + result, null, locale));
   return "redirect:/badUser.html?lang=" + locale.getLanguage();
 }
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  @PreAuthorize("hasRole('CTRL_PERM_ADD_POST')")
  public String addPermission(
      @Valid @ModelAttribute PermissionDTO permissionDTO,
      BindingResult result,
      RedirectAttributes redirectAttrs) {

    logger.debug("IN: Permission/add-POST");
    logger.debug("  DTO: " + permissionDTO.toString());

    if (result.hasErrors()) {
      logger.debug("PermissionDTO add error: " + result.toString());
      redirectAttrs.addFlashAttribute(
          "org.springframework.validation.BindingResult.permissionDTO", result);
      redirectAttrs.addFlashAttribute("permissionDTO", permissionDTO);
      return "redirect:/permission/list";
    } else {
      Permission perm = new Permission();

      try {
        perm = getPermission(permissionDTO);
        permissionService.addPermission(perm);
        String message =
            messageSource.getMessage(
                "ctrl.message.success.add",
                new Object[] {businessObject, perm.getPermissionname()},
                Locale.US);
        redirectAttrs.addFlashAttribute("message", message);
        return "redirect:/permission/list";
      } catch (DuplicatePermissionException e) {
        String message =
            messageSource.getMessage(
                "ctrl.message.error.duplicate",
                new Object[] {businessObject, permissionDTO.getPermissionname()},
                Locale.US);
        redirectAttrs.addFlashAttribute("error", message);
        return "redirect:/permission/list";
      } catch (RoleNotFoundException e) {
        String message =
            messageSource.getMessage(
                "ctrl.message.error.notfound",
                new Object[] {"role ids", permissionDTO.getPermRoles().toString()},
                Locale.US);
        redirectAttrs.addFlashAttribute("error", message);
        return "redirect:/permission/list";
      }
    }
  }
 @RequestMapping("uploadError")
 public ModelAndView onUploadError(Locale locale) {
   ModelAndView modelAndView = new ModelAndView("profile/profilePage");
   modelAndView.addObject("error", messageSource.getMessage("upload.file.too.big", null, locale));
   modelAndView.addObject("profileForm", userProfileSession.toForm());
   return modelAndView;
 }
 @ExceptionHandler(IOException.class)
 public ModelAndView handleIOException(Locale locale) {
   ModelAndView modelAndView = new ModelAndView("profile/profilePage");
   modelAndView.addObject("error", messageSource.getMessage("upload.io.exception", null, locale));
   modelAndView.addObject("profileForm", userProfileSession.toForm());
   return modelAndView;
 }
  /**
   * Map a list of Computer to a list of ComputerDTO.
   *
   * @param computers the computers to map
   * @return the computers as dto
   */
  public List<ComputerDto> listFromModel(List<Computer> computers) {
    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, LocaleContextHolder.getLocale()));
    List<ComputerDto> computersDto = new ArrayList<ComputerDto>();

    for (Computer computer : computers) {
      String introduced = null;
      String discontinued = null;
      long companyId = 0;
      String companyName = null;
      if (null != computer.getIntroduced()) {
        introduced = computer.getIntroduced().format(formatter);
      }
      if (null != computer.getDiscontinued()) {
        discontinued = computer.getDiscontinued().format(formatter);
      }
      if (null != computer.getCompany()) {
        companyId = computer.getCompany().getId();
        companyName = computer.getCompany().getName();
      }

      computersDto.add(
          new ComputerDto.ComputerDtoBuilder(computer.getName())
              .id(computer.getId())
              .companyId(companyId)
              .companyName(companyName)
              .introduced(introduced)
              .discontinued(discontinued)
              .build());
    }
    return computersDto;
  }
  /**
   * Map a ComputerDTo to a Computer.
   *
   * @param dto the ComputerDTO to map
   * @return the dto as a computer
   */
  public Computer toComputer(ComputerDto dto) {

    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, Locale.getDefault()));
    LocalDate introduced = null;
    LocalDate discontinued = null;

    if (null != dto.getIntroduced() && !dto.getIntroduced().isEmpty()) {
      introduced = LocalDate.parse(dto.getIntroduced(), formatter);
    }
    if (null != dto.getDiscontinued() && !dto.getDiscontinued().isEmpty()) {
      discontinued = LocalDate.parse(dto.getDiscontinued(), formatter);
    }
    Company company = null;
    if (dto.getCompanyId() != 0) {
      company = new Company(dto.getCompanyId(), dto.getCompanyName());
    }

    return new Computer.ComputerBuilder(dto.getName())
        .id(dto.getId())
        .company(company)
        .introduced(introduced)
        .discontinued(discontinued)
        .build();
  }
 // TODO:cannot process MultipartException
 @ExceptionHandler(MultipartException.class)
 public ModelAndView onUploadError1(Locale locale) {
   ModelAndView modelAndView = new ModelAndView("profile/profilePage");
   modelAndView.addObject("error", messageSource.getMessage("upload.file.too.big", null, locale));
   modelAndView.addObject("profileForm", userProfileSession.toForm());
   return modelAndView;
 }
示例#22
0
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String main(@ModelAttribute User user, HttpSession session, Locale locale) {
   logger.info(locale.getDisplayLanguage());
   logger.info(
       messageSource.getMessage("locale", new String[] {locale.getDisplayName(locale)}, locale));
   return "login";
 }
示例#23
0
  private void createDefaultPages(User managedUser) {
    // Create profile page
    pageRepository.createPageForUser(
        managedUser, pageTemplateRepository.getDefaultPage(PageType.PERSON_PROFILE));
    // Create default page set
    try {
      JSONArray obj = new JSONArray(messages.getMessage("user.pages.json", null, null, null));
      for (int i = 0; i < obj.length(); i++) {
        JSONObject o = obj.getJSONObject(i);

        Page page =
            pageRepository.createPageForUser(
                managedUser, pageTemplateRepository.getDefaultPage(PageType.USER));
        page.setName(o.getString("pName"));
        page.setPageLayout(pageLayoutRepository.getByPageLayoutCode(o.getString("layout")));
        pageRepository.save(page);
      }
    } catch (JSONException ex) {
      LOG.log(Level.SEVERE, null, ex);
    }

    String storageUrl = cmisBaseUrl + "/_" + HttpUtils.generateId(managedUser.getUsername());
    PersonPropertyImpl pp = new PersonPropertyImpl();
    pp.setType("urls");
    pp.setValue("storageUrl: " + storageUrl);

    managedUser.getProperties().add(pp);
  }
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  @PreAuthorize("hasRole('CTRL_PERM_EDIT_GET')")
  public String editPermissionPage(
      @RequestParam(value = "id", required = true) Integer id,
      Model model,
      RedirectAttributes redirectAttrs) {

    logger.debug("IN: Permission/edit-GET:  ID to query = " + id);

    try {
      if (!model.containsAttribute("permissionDTO")) {
        logger.debug("Adding permissionDTO object to model");
        Permission perm = permissionService.getPermission(id);
        PermissionDTO permissionDTO = getPermissionDTO(perm);
        logger.debug("Permission/edit-GET:  " + permissionDTO.toString());
        model.addAttribute("permissionDTO", permissionDTO);
      }
      return "permission-edit";
    } catch (PermissionNotFoundException e) {
      String message =
          messageSource.getMessage(
              "ctrl.message.error.notfound", new Object[] {"user id", id}, Locale.US);
      model.addAttribute("error", message);
      return "redirect:/permission/list";
    }
  }
  @RequestMapping(value = "/{id}", params = "edit", method = RequestMethod.POST)
  public String answerQuestionEdit(
      @PathVariable("id") Long id,
      QuestionAnswer questionAnswer,
      Model model,
      RedirectAttributes redirectAttributes,
      Locale locale) {
    QuestionAnswer questionAnswerTmp = questionAnswerService.findById(id);
    if (questionAnswer.getAnswer() == "" || questionAnswer.getAnswer() == null) {
      Question question = new Question();
      question.setCreationDate(questionAnswerTmp.getCreationDate());
      question.setPhone(questionAnswerTmp.getPhone());
      question.setEmail(questionAnswerTmp.getEmail());
      question.setName(questionAnswerTmp.getName());
      question.setQuestion(questionAnswerTmp.getQuestion());
      questionService.addQuestion(question);
      questionAnswerService.deleteQuestionAnswer(id);
    } else {
      questionAnswer.setCreationDate(questionAnswerTmp.getCreationDate());
      questionAnswer.setName(questionAnswerTmp.getName());
      questionAnswer.setEmail(questionAnswerTmp.getEmail());
      questionAnswer.setPhone(questionAnswerTmp.getPhone());
      questionAnswer.setId(questionAnswerTmp.getId());
      questionAnswerService.editQuestionAnswer(questionAnswer);
    }

    redirectAttributes.addFlashAttribute(
        "message",
        new Message(
            "success",
            messageSource.getMessage("question_answer_save_success", new Object[] {}, locale)));

    return "redirect:/admin/questionAnswer";
  }
示例#26
0
  /*
   * This method will be called on form submission, handling POST request for
   * saving employee in database. It also validates the user input
   */
  @RequestMapping(
      value = {"/new"},
      method = RequestMethod.POST)
  public String saveEmployee(@Valid Employee employee, BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
      return "registration";
    }

    /*
     * Preferred way to achieve uniqueness of field [ssn] should be
     * implementing custom @Unique annotation and applying it on field [ssn]
     * of Model class [Employee].
     *
     * Below mentioned peace of code [if block] is to demonstrate that you
     * can fill custom errors outside the validation framework as well while
     * still using internationalized messages.
     */
    if (!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())) {
      FieldError ssnError =
          new FieldError(
              "employee",
              "ssn",
              messageSource.getMessage(
                  "non.unique.ssn", new String[] {employee.getSsn()}, Locale.getDefault()));
      result.addError(ssnError);
      return "registration";
    }
    employee.setId(service.getNext().intValue());
    service.saveEmployee(employee);

    model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
    return "success";
  }
示例#27
0
  /*
   * This method will be called on form submission, handling POST request for
   * updating employee in database. It also validates the user input
   */
  @RequestMapping(
      value = {"/edit-{ssn}-employee"},
      method = RequestMethod.POST)
  public String updateEmployee(
      @Valid Employee employee, BindingResult result, ModelMap model, @PathVariable String ssn) {

    if (result.hasErrors()) {
      return "registration";
    }

    if (!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())) {
      FieldError ssnError =
          new FieldError(
              "employee",
              "ssn",
              messageSource.getMessage(
                  "non.unique.ssn", new String[] {employee.getSsn()}, Locale.getDefault()));
      result.addError(ssnError);
      return "registration";
    }

    service.updateEmployee(employee);

    model.addAttribute("success", "Employee " + employee.getName() + " updated successfully");
    return "success";
  }
  @Before
  public void setUp() {
    MessageSourceMacroDescriptor desc = new MessageSourceMacroDescriptor(MACRO);
    Whitebox.setInternalState(desc, messageSource);

    when(beanFactory.getBean(MessageSourceMacroDescriptor.ID, MACRO)).thenReturn(desc);

    when(messageSource.getMessage(
            "macro." + MACRO + ".title", null, LOCALE)) // $NON-NLS-1$ //$NON-NLS-2$
        .thenReturn(TITLE);
    when(messageSource.getMessage(
            "macro." + MACRO + ".description", null, LOCALE)) // $NON-NLS-1$ //$NON-NLS-2$
        .thenReturn(DESCRIPTION);

    descriptor = MessageSourceMacroDescriptor.create(MACRO, beanFactory);
  }
示例#29
0
  @RequestMapping(value = "users/edit_my_account", method = RequestMethod.POST)
  public String editMyAccountSubmitHandler(
      Model model,
      Locale locale,
      @Valid @ModelAttribute("userFormBean") UserFormBean userFormBean,
      BindingResult result,
      final RedirectAttributes redirectAttributes,
      Principal principal) {

    logger.debug("UserController.editMyAccountSubmitHandler is invoked.");

    User editUser = authorityService.findUserByUserId(principal.getName());

    if (result.hasErrors()) {
      Group editUserGroup = editUser.getGroup();
      model.addAttribute("editUserGroup", editUserGroup);

      return "users/edit_my_account";
    } else {
      editUser.setName(userFormBean.getName());
      editUser.setPassword(userFormBean.getPassword());
      editUser.setEmail(userFormBean.getEmail());

      authorityService.persist(editUser);

      redirectAttributes.addFlashAttribute(
          "info",
          messageSource.getMessage(
              "users.info.edit_user_success", new String[] {editUser.getUserId()}, locale));
      return "redirect:/";
    }
  }
示例#30
0
  @Async
  @Override
  public void enviarMailCambioContraseña(String nombre, String email, String token, Locale locale) {
    try {
      final Context ctx = new Context(locale);
      ctx.setVariable("nombre", nombre);
      ctx.setVariable("token", token);
      ctx.setVariable("lenguaje", locale.getLanguage());

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
      message.setSubject(messageSource.getMessage("reset.email.titulo", null, locale));
      message.setFrom("*****@*****.**", "Cudú");
      message.setTo(email);

      final String htmlContent = templateEngine.process("resetpassword", ctx);
      message.setText(htmlContent, true);
      mailSender.send(mimeMessage);
    } catch (Exception e) {
      String correlationId = UUID.randomUUID().toString();
      Marker marker = MarkerFactory.getMarker("ENVIO_EMAIL");
      logger.error(
          marker, "Error enviando email. Token: " + token + ", CorrelationId: " + correlationId, e);
      eventPublisher.publishEvent(new EmailErrorApplicationEvent(email, correlationId));
    }
  }