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); }
@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; }
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); }
/** @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; }
@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; }
@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"; }
/** * 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() + "'"); } }
/** @see MessageFactory#renderString(String, Object[]) */ public final String renderString(final String message, final Object[] params) { return resourceBundleMessageSource.getMessage(message, params, Locale.getDefault()); }
@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; }