@Bean
 public MessageSource messageSource() {
   ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
   messageSource.setBasenames(
       getResourceBundleLocations().toArray(new String[getResourceBundleLocations().size()]));
   return messageSource;
 }
示例#2
0
 @Bean
 public MessageSource messageSource() {
   ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
   ms.setBasenames("message.error");
   ms.setDefaultEncoding("UTF-8");
   return ms;
 }
 @RolesAllowed(value = {"ROLE_USER"})
 @RequestMapping(method = RequestMethod.POST, value = "/uploadMeta", produces = "application/json")
 @ResponseBody
 public Map<String, Object> saveUploadMetadata(
     HttpServletRequest request, @RequestBody PresentationMetaDTO presentationData) {
   Map<String, Object> result = null;
   Presentation data =
       new Presentation(
           presentationData.getTitle(),
           presentationData.getDescription(),
           presentationData.getSlideDuration());
   try {
     if (data.isValidData()) {
       Cathegory cat = getCathegoryByName(presentationData.getCathegory());
       data.setUser(getCurrentUser());
       data.setCathegory(cat);
       HttpSession session = request.getSession();
       session.setAttribute(UPLOAD_METADATA, data);
       result = JsonUtils.successJson();
     } else {
       result =
           JsonUtils.failureJson(
               messages.getMessage("validation.upload.data.is.incorect", null, null));
     }
   } catch (PresentationException e) {
     result =
         JsonUtils.failureJson(
             messages.getMessage("validation.upload.data.is.incorect", null, null));
   }
   return result;
 }
示例#4
0
 @Bean
 public MessageSource messageSource() {
   ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
   messageSource.setBasename("messages");
   messageSource.setAlwaysUseMessageFormat(true);
   return messageSource;
 }
  private void enviaCorreo(String tipo, List<Almacen> almacenes, HttpServletRequest request)
      throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;
    switch (tipo) {
      case "PDF":
        archivo = generaPdf(almacenes);
        tipoContenido = "application/pdf";
        break;
      case "CSV":
        archivo = generaCsv(almacenes);
        tipoContenido = "text/csv";
        break;
      case "XLS":
        archivo = generaXls(almacenes);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("almacen.lista.label", null, request.getLocale());
    helper.setSubject(
        messageSource.getMessage(
            "envia.correo.titulo.message", new String[] {titulo}, request.getLocale()));
    helper.setText(
        messageSource.getMessage(
            "envia.correo.contenido.message", new String[] {titulo}, request.getLocale()),
        true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
  }
  @Bean
  @Description("Spring message resolver")
  public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("i18n/messages");

    return messageSource;
  }
 @Bean
 public ResourceBundleMessageSource messageSource() {
   ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
   messageSource.setBasename("messages");
   messageSource.setUseCodeAsDefaultMessage(true);
   messageSource.setDefaultEncoding("UTF-8");
   return messageSource;
 }
  @Bean(name = "messageSource")
  public ResourceBundleMessageSource resourceBundleMessageSource() {

    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("WEB-INF/messages/messages");
    messageSource.setDefaultEncoding("UTF-8");

    return messageSource;
  }
 /**
  * Bean koji sluzi da bi locirali properties datoteke za poruke.
  *
  * @return
  */
 @Bean
 public ResourceBundleMessageSource messageSource() {
   final ResourceBundleMessageSource source = new ResourceBundleMessageSource();
   String[] basenamesSpecific = {
     "properties.messages.common.messages", "properties.messages.app.application"
   };
   source.setBasenames(basenamesSpecific);
   source.setUseCodeAsDefaultMessage(true);
   source.setDefaultEncoding("UTF-8");
   return source;
 }
示例#10
0
  protected final void setUp() throws Exception {

    String[] files = {
      "/org/hdiv/config/hdiv-core-applicationContext.xml",
      "/org/hdiv/config/hdiv-config.xml",
      "/org/hdiv/config/hdiv-validations.xml",
      "/org/hdiv/config/applicationContext-test.xml"
    };

    if (this.applicationContext == null) {
      this.applicationContext = new ClassPathXmlApplicationContext(files);
    }

    // Servlet API mock
    HttpServletRequest request =
        (MockHttpServletRequest) this.applicationContext.getBean("mockRequest");
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    HDIVUtil.setHttpServletRequest(request);

    // Initialize config
    this.config = (HDIVConfig) this.applicationContext.getBean("config");

    // Initialize HttpSession
    InitListener initListener = new InitListener();
    initListener.setConfig(this.config);
    initListener.initStrategies(this.applicationContext, httpSession);
    initListener.initCache(this.applicationContext, httpSession);
    initListener.initPageIdGenerator(this.applicationContext, httpSession);
    initListener.initHDIVState(this.applicationContext, httpSession);

    // Initialize HDIVConfig in ServletContext
    HDIVUtil.setHDIVConfig(this.config, servletContext);

    // Initialize IApplication in ServletContext
    IApplication application = (IApplication) this.applicationContext.getBean("application");
    HDIVUtil.setApplication(application, servletContext);

    // Initialize MessageSource in ServletContext
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBeanClassLoader(this.applicationContext.getClassLoader());
    String messageSourcePath = (String) this.applicationContext.getBean("messageSourcePath");
    messageSource.setBasename(messageSourcePath);
    HDIVUtil.setMessageSource(messageSource, servletContext);

    // Initialize the IDataComposer
    DataComposerFactory dataComposerFactory =
        (DataComposerFactory) this.applicationContext.getBean("dataComposerFactory");
    IDataComposer dataComposer = dataComposerFactory.newInstance();
    HDIVUtil.setDataComposer(dataComposer, request);

    onSetUp();
  }
示例#11
0
  @Bean
  public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

    messageSource.setBasename(
        environment.getRequiredProperty(PROPERTY_NAME_MESSAGESOURCE_BASENAME));
    messageSource.setUseCodeAsDefaultMessage(
        Boolean.parseBoolean(
            environment.getRequiredProperty(
                PROPERTY_NAME_MESSAGESOURCE_USE_CODE_AS_DEFAULT_MESSAGE)));

    return messageSource;
  }
示例#12
0
  /** @see #formattedMessage */
  public String getFormattedMessage() {
    // resolve msg somente na primeira vez
    if (formattedMessage == null && i18nMessage != null) {
      List<ResourceBundle> rbs = this.source.getApplication().getResouceBundle();
      if (rbs != null) {
        for (ResourceBundle rb : rbs) {
          try {
            String msg = rb.getString(i18nMessage);
            if (msg != null) {
              formattedMessage = MessageFormat.format(msg, param.toArray(new Object[] {}));
              break;
            }
          } catch (MissingResourceException mre) {
            // silently igonre
            continue;
          }
        }
      }
    }

    // verifica msgs da platforma
    if (StringUtils.isBlank(formattedMessage)) {
      List<ResourceBundleMessageSource> rbs =
          PlatformMessageRegistry.getInstance().getMessageBundles();
      if (rbs != null) {
        for (ResourceBundleMessageSource rb : rbs) {
          try {
            String msg =
                rb.getMessage(
                    i18nMessage,
                    param.toArray(new Object[] {}),
                    source.getApplication().getCurrentLocale());

            formattedMessage = msg;
            break;

          } catch (NoSuchMessageException nsme) {
            // silently igonre
            continue;
          }
        }
      }
    }

    if (StringUtils.isBlank(formattedMessage)) {
      formattedMessage = MessageFormat.format(i18nMessage, param.toArray(new Object[] {}));
    }

    return formattedMessage;
  }
示例#13
0
 public ResourceBundleMessageSource getRes() {
   if (res == null) {
     res = new ResourceBundleMessageSource();
     res.setBasenames(new String[] {"res/messages"});
   }
   return res;
 }
示例#14
0
 private void prepareEvent() {
   Map<String, Object> params = new HashMap<>();
   params.put(EMAIL_PARAM_FROM_ADDRESS, SENDER_ADDRESS);
   params.put(EMAIL_PARAM_TO_ADDRESS, user.getEmail());
   params.put(EMAIL_PARAM_MESSAGE, EMAIL_MESSAGE);
   params.put(
       EMAIL_PARAM_SUBJECT,
       messageSource.getMessage(PASSWORD_CHANGE_REMINDER_MESSAGE_SUBJECT, null, Locale.ENGLISH));
   event = new MotechEvent("SendEMail", params);
 }
 @Override
 public void setBasenames(final String... basenames) {
   List<String> list = new LinkedList<String>();
   if (CollectionUtils.isEmpty(basenames)) return;
   for (String baseName : basenames) {
     if (StringUtils.isEmpty(baseName)) continue;
     String[] bases = StringUtils.split(baseName, ',');
     for (String base : bases) {
       list.add("classpath:i18n/" + base);
     }
   }
   String[] bases = new String[list.size()];
   list.toArray(bases);
   list.clear();
   list = null;
   super.setBasenames(bases);
 }
示例#16
0
 @RolesAllowed(value = {"ROLE_USER"})
 @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "application/json")
 @ResponseBody
 public Map<String, Object> uploadFile(
     HttpServletRequest req, @RequestParam("fileData") CommonsMultipartFile uploadedFile) {
   Map<String, Object> result = null;
   if (uploadedFile == null) {
     result = JsonUtils.failureJson();
   } else {
     try {
       if (uploadedFile.isEmpty()) {
         String errorMessage = messages.getMessage("validation.upload.file.is.empty", null, null);
         result = JsonUtils.failureJson(errorMessage);
       } else {
         HttpSession session = req.getSession();
         Presentation data = uploadFileToRepo(uploadedFile, session);
         if (data != null) {
           Long id = baseDao.save(data);
           Job job = new Job(id);
           queue.send(job, UPLOAD_QUEUE);
           result =
               JsonUtils.successWithParameter(
                   JsonUtils.PARAM_MESSAGE, messages.getMessage("upload.success", null, null));
         } else {
           String errorMessage =
               messages.getMessage("validation.upload.first.set.metadata", null, null);
           result = JsonUtils.failureJson(errorMessage);
         }
         session.removeAttribute(UPLOAD_METADATA);
       }
     } catch (UploadedDataNotFoundException e) {
       String errorMessage =
           messages.getMessage("validation.upload.first.set.metadata", null, null);
       result = JsonUtils.failureJson(errorMessage);
     } catch (IllegalStateException | IOException e) {
       String errorMessage = messages.getMessage("validation.upload.failed", null, null);
       result = JsonUtils.failureJson(errorMessage);
     } catch (IncorectFileException e) {
       String errorMessage =
           messages.getMessage("validation.upload.incorect.file.extension", null, null);
       String acceptedEx = getExtensions(acceptedExtensions);
       result = JsonUtils.failureJson(errorMessage + acceptedEx);
     }
   }
   return result;
 }
  /**
   * Generates the request summary with given request id in csv format for downloading
   *
   * @param requestId
   * @param resourceRequest
   * @param response
   */
  @ResourceMapping(value = "exportFile")
  public void download(
      @RequestParam(value = "newRequestId") String requestId,
      ResourceRequest resourceRequest,
      ResourceResponse response) {
    response.setContentType("text/csv; charset=utf-8");
    EmployeeRequestHandle reqhandle = new EmployeeRequestHandle();
    KokuRequest kokuRequest = null;
    try {
      kokuRequest = reqhandle.getKokuRequestById(requestId);
      if (kokuRequest == null) {
        LOG.error("getKokuRequestById returned null. requestId: '" + requestId + "'");
        return;
      }
    } catch (KokuServiceException kse) {
      LOG.error(
          "Error when trying to create CSV export. WS doesn't work properly. requestId: '"
              + requestId
              + "'",
          kse);
    }
    String requestSubject = kokuRequest.getSubject();
    if (requestSubject == null || requestSubject.isEmpty()) {
      requestSubject = "vastaus";
    }

    /* Note: Do not change Pragma and Cache-Control values. Otherwise IE doesn't recognize
     * CSV file properly when using HTTPS. See http://support.microsoft.com/kb/316431 for more details.
     * This is issue with IE5 - IE9 versions. */
    response.setProperty("Pragma", "private");
    response.setProperty("Cache-Control", "private, must-revalidate");

    response.setProperty("Content-Disposition", "attachment; filename=" + requestSubject + ".csv");
    response.setProperty("Content-Type", "text/xml, charset=UTF-8; encoding=UTF-8");

    final String username = resourceRequest.getUserPrincipal().getName();
    final Locale locale = MessageUtil.getLocale();
    PrintWriter responseWriter = null;
    try {
      responseWriter = response.getWriter();
      final BufferedWriter writer = new BufferedWriter(responseWriter);
      /* UTF-8 BOM (Do not remove, otherwise Excel won't recognize characters correctly!) */
      writer.append('\uFEFF');
      /* Headers */
      writer.write(addQuote(messageSource.getMessage("export.responseSummary", null, locale)));
      writer.write(NEW_LINE);
      writer.write(
          addQuote(messageSource.getMessage("export.respondent", null, locale)) + SEPARATOR);

      for (KokuQuestion q : kokuRequest.getQuestions()) {
        writer.write(addQuote(q.getDescription()) + SEPARATOR);
      }
      writer.write(addQuote(messageSource.getMessage("export.comment", null, locale)));
      writer.write(NEW_LINE);

      /* Data */
      for (KokuResponse res : kokuRequest.getRespondedList()) {
        writer.write(addQuote(res.getReplierUser().getFullName()) + SEPARATOR);
        Collections.sort(res.getAnswers(), SORT_BY_ANSWER_NUMBER);
        for (KokuAnswer answer : res.getAnswers()) {
          if (answer != null) {
            writer.write(addQuote(answer.getAnswer()) + SEPARATOR);
          }
        }
        writer.write(addQuote(res.getComment()));
        writer.write(NEW_LINE);
      }

      writer.write(NEW_LINE);
      writer.write(addQuote(messageSource.getMessage("export.missed", null, locale)));
      writer.write(NEW_LINE);

      for (KokuUser name : kokuRequest.getUnrespondedList()) {
        writer.write(addQuote(name.getFullName()));
        writer.write(NEW_LINE);
      }
      writer.flush();
      writer.close();
    } catch (IOException e) {
      LOG.error(
          "Generate csv file failed. Username: '******'  RequestId: '"
              + kokuRequest.getRequestId()
              + "'");
    }
  }
示例#18
0
  @RequestMapping
  public String lista(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam(required = false) String filtro,
      @RequestParam(required = false) Long pagina,
      @RequestParam(required = false) String tipo,
      @RequestParam(required = false) String correo,
      @RequestParam(required = false) String order,
      @RequestParam(required = false) String sort,
      Usuario usuario,
      Errors errors,
      Model modelo) {
    log.debug("Mostrando lista de tipos de entradas");
    Map<String, Object> params = new HashMap<>();
    params.put("almacen", request.getSession().getAttribute("almacenId"));
    if (StringUtils.isNotBlank(filtro)) {
      params.put("filtro", filtro);
    }
    if (pagina != null) {
      params.put("pagina", pagina);
      modelo.addAttribute("pagina", pagina);
    } else {
      pagina = 1L;
      modelo.addAttribute("pagina", pagina);
    }
    if (StringUtils.isNotBlank(order)) {
      params.put("order", order);
      params.put("sort", sort);
    }

    if (StringUtils.isNotBlank(tipo)) {
      params.put("reporte", true);
      params = entradaDao.lista(params);
      try {
        generaReporte(tipo, (List<Entrada>) params.get("entradas"), response);
        return null;
      } catch (JRException | IOException e) {
        log.error("No se pudo generar el reporte", e);
        params.remove("reporte");
        errors.reject("error.generar.reporte");
      }
    }

    if (StringUtils.isNotBlank(correo)) {
      params.put("reporte", true);
      params = entradaDao.lista(params);

      params.remove("reporte");
      try {
        enviaCorreo(correo, (List<Entrada>) params.get("entradas"), request);
        modelo.addAttribute("message", "lista.enviada.message");
        modelo.addAttribute(
            "messageAttrs",
            new String[] {
              messageSource.getMessage("entrada.lista.label", null, request.getLocale()),
              ambiente.obtieneUsuario().getUsername()
            });
      } catch (JRException | MessagingException e) {
        log.error("No se pudo enviar el reporte por correo", e);
      }
    }
    params = entradaDao.lista(params);
    modelo.addAttribute("entradas", params.get("entradas"));

    // inicia paginado
    Long cantidad = (Long) params.get("cantidad");
    Integer max = (Integer) params.get("max");
    Long cantidadDePaginas = cantidad / max;
    List<Long> paginas = new ArrayList<>();
    long i = 1;
    do {
      paginas.add(i);
    } while (i++ < cantidadDePaginas);
    List<Entrada> entradas = (List<Entrada>) params.get("entradas");
    Long primero = ((pagina - 1) * max) + 1;
    Long ultimo = primero + (entradas.size() - 1);
    String[] paginacion = new String[] {primero.toString(), ultimo.toString(), cantidad.toString()};
    modelo.addAttribute("paginacion", paginacion);
    modelo.addAttribute("paginas", paginas);
    // termina paginado

    return "inventario/entrada/lista";
  }
示例#19
0
 @Bean
 public ResourceBundleMessageSource messageSource() {
   ResourceBundleMessageSource source = new ResourceBundleMessageSource();
   source.setBasename("messages");
   return source;
 }
示例#20
0
 private void prepareMessageSource() {
   messageSource = new ResourceBundleMessageSource();
   messageSource.setBasename("messages/messages");
   messageSource.setUseCodeAsDefaultMessage(true);
 }
  @RequestMapping({"", "/lista"})
  public String lista(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam(required = false) String filtro,
      @RequestParam(required = false) Long pagina,
      @RequestParam(required = false) String tipo,
      @RequestParam(required = false) String correo,
      @RequestParam(required = false) String order,
      @RequestParam(required = false) String sort,
      Usuario usuario,
      Errors errors,
      Model modelo) {
    log.debug("Mostrando lista de tipos de Becas");
    Map<String, Object> params = new HashMap<>();
    Long empresaId = (Long) request.getSession().getAttribute("empresaId");
    params.put("empresa", empresaId);
    if (StringUtils.isNotBlank(filtro)) {
      params.put(Constantes.CONTAINSKEY_FILTRO, filtro);
    }
    if (pagina != null) {
      params.put(Constantes.CONTAINSKEY_PAGINA, pagina);
      modelo.addAttribute(Constantes.CONTAINSKEY_PAGINA, pagina);
    } else {
      pagina = 1L;
      modelo.addAttribute(Constantes.CONTAINSKEY_PAGINA, pagina);
    }
    if (StringUtils.isNotBlank(order)) {
      params.put(Constantes.CONTAINSKEY_ORDER, order);
      params.put(Constantes.CONTAINSKEY_SORT, sort);
    }

    if (StringUtils.isNotBlank(tipo)) {
      params.put(Constantes.CONTAINSKEY_REPORTE, true);
      params = alumnoPaqueteManager.lista(params);
      try {
        generaReporte(
            tipo,
            (List<AlumnoPaquete>) params.get(Constantes.CONTAINSKEY_ALUMNOPAQUETES),
            response);
        return null;
      } catch (JRException | IOException e) {
        log.error("No se pudo generar el reporte", e);
        params.remove(Constantes.CONTAINSKEY_REPORTE);
        // errors.reject("error.generar.reporte");
      }
    }

    if (StringUtils.isNotBlank(correo)) {
      params.put(Constantes.CONTAINSKEY_REPORTE, true);
      params = alumnoPaqueteManager.lista(params);

      params.remove(Constantes.CONTAINSKEY_REPORTE);
      try {
        enviaCorreo(
            correo,
            (List<AlumnoPaquete>) params.get(Constantes.CONTAINSKEY_ALUMNOPAQUETES),
            request);
        modelo.addAttribute(Constantes.CONTAINSKEY_MESSAGE, "lista.enviada.message");
        modelo.addAttribute(
            Constantes.CONTAINSKEY_MESSAGE_ATTRS,
            new String[] {
              messageSource.getMessage("alumnoPaquete.lista.label", null, request.getLocale()),
              ambiente.obtieneUsuario().getUsername()
            });
      } catch (JRException | MessagingException e) {
        log.error("No se pudo enviar el reporte por correo", e);
      }
    }
    params = alumnoPaqueteManager.lista(params);
    log.debug("params{}", params.get(Constantes.CONTAINSKEY_ALUMNOPAQUETES));
    modelo.addAttribute(
        Constantes.CONTAINSKEY_ALUMNOPAQUETES, params.get(Constantes.CONTAINSKEY_ALUMNOPAQUETES));

    // inicia paginado
    Long cantidad = (Long) params.get(Constantes.CONTAINSKEY_CANTIDAD);
    Integer max = (Integer) params.get(Constantes.CONTAINSKEY_MAX);
    Long cantidadDePaginas = cantidad / max;
    List<Long> paginas = new ArrayList<>();
    long i = 1;
    do {
      paginas.add(i);
    } while (i++ < cantidadDePaginas);
    List<AlumnoPaquete> alumnoPaquetes =
        (List<AlumnoPaquete>) params.get(Constantes.CONTAINSKEY_ALUMNOPAQUETES);
    Long primero = ((pagina - 1) * max) + 1;
    log.debug("primero {}", primero);
    Long ultimo = primero + (alumnoPaquetes.size() - 1);
    String[] paginacion = new String[] {primero.toString(), ultimo.toString(), cantidad.toString()};
    modelo.addAttribute(Constantes.CONTAINSKEY_PAGINACION, paginacion);
    log.debug("Paginacion{}", paginacion);
    modelo.addAttribute(Constantes.CONTAINSKEY_PAGINAS, paginas);
    log.debug("paginas{}", paginas);
    modelo.addAttribute(Constantes.CONTAINSKEY_PAGINA, pagina);
    log.debug("Pagina{}", pagina);
    // termina paginado

    return Constantes.PATH_ALUMNOPAQUETE_LISTA;
  }
 /** @see MessageFactory#renderString(String, Object[]) */
 public final String renderString(final String message, final Object[] params) {
   return resourceBundleMessageSource.getMessage(message, params, Locale.getDefault());
 }
 // Provides internationalization of messages
 @Bean
 public ResourceBundleMessageSource messageSource() {
   ResourceBundleMessageSource source = new ResourceBundleMessageSource();
   source.setBasenames(new String[] {"i18n/message"});
   return source;
 }
示例#24
0
 @Bean
 public MessageSource messageSource() {
   ResourceBundleMessageSource resourceMessage = new ResourceBundleMessageSource();
   resourceMessage.setBasename("message");
   return resourceMessage;
 }