List of usage examples for javax.servlet.http HttpServletRequest getLocale
public Locale getLocale();
Locale
that the client will accept content in, based on the Accept-Language header. From source file:mx.edu.um.mateo.rh.web.VacacionesEmpleadoController.java
private void enviaCorreo(String tipo, List<VacacionesEmpleado> vacacionesEmpleados, HttpServletRequest request) throws JRException, MessagingException { log.debug("Enviando correo {}", tipo); byte[] archivo = null; String tipoContenido = null;/* w ww .j av a 2 s . c o m*/ switch (tipo) { case "PDF": archivo = generaPdf(vacacionesEmpleados); tipoContenido = "application/pdf"; break; case "CSV": archivo = generaCsv(vacacionesEmpleados); tipoContenido = "text/csv"; break; case "XLS": archivo = generaXls(vacacionesEmpleados); tipoContenido = "application/vnd.ms-excel"; } MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(ambiente.obtieneUsuario().getUsername()); String titulo = messageSource.getMessage("vacacionesEmpleado.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); }
From source file:alpha.portal.webapp.controller.UserFormController.java
/** * On submit.// w ww. java 2 s . co m * * @param user * the user * @param errors * the errors * @param request * the request * @param response * the response * @param model * the model * @return the string * @throws Exception * the exception */ @RequestMapping(method = RequestMethod.POST) public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request, final HttpServletResponse response, final Model model) throws Exception { if (request.getParameter("cancel") != null) { if (!StringUtils.equals(request.getParameter("from"), "list")) return this.getCancelView(); else return this.getSuccessView(); } if (this.validator != null) { // validator is null during testing this.validator.validate(user, errors); if (errors.hasErrors() && (request.getParameter("delete") == null)) { model.addAttribute("contributorRoles", this.contributorRoleManager.getAll()); return "userform"; } } this.log.debug("entering 'onSubmit' method..."); final Locale locale = request.getLocale(); if (request.getParameter("delete") != null) { this.getUserManager().removeUser(user.getId().toString()); this.saveMessage(request, this.getText("user.deleted", user.getFullName(), locale)); return this.getSuccessView(); } else { // only attempt to change roles if user is admin for other users, // showForm() method will handle populating if (request.isUserInRole(Constants.ADMIN_ROLE)) { final String[] userRoles = request.getParameterValues("userRoles"); if (userRoles != null) { user.getRoles().clear(); for (final String roleName : userRoles) { user.addRole(this.roleManager.getRole(roleName)); } } } final Integer originalVersion = user.getVersion(); try { this.getUserManager().saveUser(user); } catch (final AccessDeniedException ade) { // thrown by UserSecurityAdvice configured in aop:advisor // userManagerSecurity this.log.warn(ade.getMessage()); response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (final UserExistsException e) { errors.rejectValue("username", "errors.existing.user", new Object[] { user.getUsername(), user.getEmail() }, "duplicate user"); // redisplay the unencrypted passwords user.setPassword(user.getConfirmPassword()); // reset the version # to what was passed in user.setVersion(originalVersion); model.addAttribute("contributorRoles", this.contributorRoleManager.getAll()); return "userform"; } if (!StringUtils.equals(request.getParameter("from"), "list")) { this.saveMessage(request, this.getText("user.saved", user.getFullName(), locale)); // return to main Menu return this.getCancelView(); } else { if (StringUtils.isBlank(request.getParameter("version"))) { this.saveMessage(request, this.getText("user.added", user.getFullName(), locale)); // Send an account information e-mail this.message.setSubject(this.getText("signup.email.subject", locale)); try { this.sendUserMessage(user, this.getText("newuser.email.message", user.getFullName(), locale), RequestUtil.getAppURL(request)); } catch (final MailException me) { this.saveError(request, me.getCause().getLocalizedMessage()); } return this.getSuccessView(); } else { this.saveMessage(request, this.getText("user.updated.byAdmin", user.getFullName(), locale)); } } } return "redirect:/mainMenu"; }
From source file:it.cilea.osd.jdyna.web.controller.ImportAnagraficaObject.java
/** Performa l'import da file xml di configurazioni di oggetti; * Sull'upload del file la configurazione dell'oggetto viene caricato come contesto di spring * e salvate su db./*from w ww. j av a2 s .c om*/ */ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws RuntimeException, IOException { FileUploadConfiguration bean = (FileUploadConfiguration) object; MultipartFile file = (CommonsMultipartFile) bean.getFile(); File a = null; //creo il file temporaneo che sara' caricato come contesto di spring per caricare la configurazione degli oggetti a = File.createTempFile("jdyna", ".xml", new File(path)); file.transferTo(a); ApplicationContext context = null; try { context = new FileSystemXmlApplicationContext(new String[] { "file:" + a.getAbsolutePath() }); } catch (XmlBeanDefinitionStoreException exc) { //cancello il file dalla directory temporanea logger.warn("Error during the configuration import from file: " + file.getOriginalFilename(), exc); a.delete(); saveMessage(request, getText("action.file.nosuccess.upload", new Object[] { exc.getMessage() }, request.getLocale())); return new ModelAndView(getErrorView()); } //cancello il file dalla directory temporanea a.delete(); String[] tpDefinitions = context.getBeanDefinitionNames(); //getBeanNamesForType(tpClass); AnagraficaObject<P, TP> anagraficaObject = null; String idStringAnagraficaObject = request.getParameter("id"); Integer pkey = Integer.parseInt(idStringAnagraficaObject); anagraficaObject = applicationService.get(modelClass, pkey); //la variabile i conta le tipologie caricate con successo int i = 0; //la variabile j conta le tipologie non caricate int j = 0; for (String tpNameDefinition : tpDefinitions) { try { ImportPropertyAnagraficaUtil importBean = (ImportPropertyAnagraficaUtil) context .getBean(tpNameDefinition); anagraficaUtils.importProprieta(anagraficaObject, importBean); } catch (Exception ecc) { saveMessage(request, getText("action.file.nosuccess.metadato.upload", new Object[] { ecc.getMessage() }, request.getLocale())); j++; i--; } i++; } //pulisco l'anagrafica anagraficaObject.pulisciAnagrafica(); applicationService.saveOrUpdate(modelClass, anagraficaObject); saveMessage(request, getText("action.file.success.upload", new Object[] { new String("Totale Oggetti Caricati:" + (i + j) + "" + "[" + i + " caricate con successo/" + j + " fallito caricamento]") }, request.getLocale())); return new ModelAndView(getDetailsView()); }
From source file:mx.edu.um.mateo.rh.web.ClaveEmpleadoController.java
private void enviaCorreo(String tipo, List<ClaveEmpleado> claveEmpleados, HttpServletRequest request) throws JRException, MessagingException { log.debug("Enviando correo {}", tipo); byte[] archivo = null; String tipoContenido = null;//from w w w. ja va2 s . c om switch (tipo) { case "PDF": archivo = generaPdf(claveEmpleados); tipoContenido = "application/pdf"; break; case "CSV": archivo = generaCsv(claveEmpleados); tipoContenido = "text/csv"; break; case "XLS": archivo = generaXls(claveEmpleados); tipoContenido = "application/vnd.ms-excel"; } MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(ambiente.obtieneUsuario().getUsername()); String titulo = messageSource.getMessage("claveEmpleado.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); }
From source file:fr.paris.lutece.plugins.crm.modules.form.service.draft.CRMDraftBackupService.java
/** * Updates the CRM status to "in progress". * @param request the request/*from w w w .j a va 2 s.c o m*/ */ private void updateCRMStatus(HttpServletRequest request) { HttpSession session = request.getSession(); // get draft blob id String strKey = (String) session.getAttribute(Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS); String strIdDemand = (String) session.getAttribute(Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS); String strCrmWebAppCode = (String) session .getAttribute(Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS); String strStatusText = I18nService.getLocalizedString(Constants.PROPERTY_CRM_STATUS_TEXT_MODIF, request.getLocale()); if (StringUtils.isNotBlank(strKey)) { try { _crmClientService.sendUpdateDemand(strIdDemand, strStatusText, strCrmWebAppCode, CrmClientConstants.CRM_STATUS_DRAFT, strKey); } catch (CRMException e) { AppLogService.error(e); } } else { _logger.error("No draft found"); } }
From source file:fr.paris.lutece.plugins.extend.modules.opengraph.web.component.OpengraphResourceExtenderComponent.java
/** * Get the header of a social hub extender for a given resource * @param config The configuration// ww w .j a va 2 s.c o m * @param extendableResource The resource * @param request The request * @return The HTML content to display */ private String getHeader(OpengraphExtenderConfig config, IExtendableResource extendableResource, HttpServletRequest request) { List<Integer> listSocialHubId = config.getListOpengraphSocialHubId(); List<String> listSocialHubs; if (listSocialHubId.isEmpty()) { listSocialHubs = Collections.emptyList(); } else { listSocialHubs = new ArrayList<String>(listSocialHubId.size()); for (OpengraphSocialHub socialHub : _opengraphService.findAll()) { if (listSocialHubId.contains(socialHub.getOpengraphSocialHubId())) { listSocialHubs.add(socialHub.getContentHeader()); } } } Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_META_TAGS, getMetaTags(extendableResource, request)); model.put(MARK_SOCIALHUBS, listSocialHubs); HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_SOCIAL_HEADER, request.getLocale(), model); return template.getHtml(); }
From source file:fr.paris.lutece.plugins.extend.web.ResourceExtenderJspBean.java
/** * Get the page to create an extender//from w ww . j a va 2s .c o m * @param request The request * @return The HTML to display */ public String getCreateResourceExtender(HttpServletRequest request) { Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_RESOURCE_TYPES, _resourceTypeService.findAllAsRef(AdminUserService.getLocale(request))); model.put(MARK_EXTENDER_TYPES, _extenderService.getExtenderTypes(request.getLocale())); model.put(MARK_MANAGE_BY_RESOURCE, Boolean.parseBoolean(request.getParameter(MARK_MANAGE_BY_RESOURCE))); HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_CREATE_RESOURCE_EXTENDER, request.getLocale(), model); return getAdminPage(template.getHtml()); }
From source file:net.bull.javamelody.TestMonitoringFilter.java
/** Test. * @throws ServletException e// w w w . j a va2 s . c om * @throws IOException e */ @Test public void testDoFilterWithSessionBis() throws ServletException, IOException { final HttpServletRequest request = createNiceMock(HttpServletRequest.class); final HttpSession session = createNiceMock(HttpSession.class); expect(request.getSession(false)).andReturn(session); // Locale sans pays expect(request.getLocale()).andReturn(Locale.FRENCH).anyTimes(); // "X-Forwarded-For" expect(request.getHeader("X-Forwarded-For")).andReturn("somewhere").anyTimes(); // getRemoteUser expect(request.getRemoteUser()).andReturn("me").anyTimes(); replay(session); doFilter(request); verify(session); }
From source file:org.shept.services.jcaptcha.ImageCaptchaServlet.java
@SuppressWarnings("unchecked") protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { BufferedImage challenge = null; try {/*w ww .j ava 2 s. c o m*/ // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id // is a good candidate! String captchaId = httpServletRequest.getSession().getId(); // If we have an explicit configuration for an ImageService we use this // else we use the predefined default ImageCaptchaService captchaService = CaptchaServiceSingleton.getInstance(); Map services = ctx.getBeansOfType(ImageCaptchaService.class); // there must be exactly on service configured if (services.size() == 1) { for (Iterator iterator = services.values().iterator(); iterator.hasNext();) { captchaService = (ImageCaptchaService) iterator.next(); } } // call the ImageCaptchaService getChallenge method challenge = captchaService.getImageChallengeForID(captchaId, httpServletRequest.getLocale()); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (CaptchaServiceException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // flush it in the response httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); ImageIO.write(challenge, "jpeg", responseOutputStream); responseOutputStream.flush(); responseOutputStream.close(); }
From source file:com.runwaysdk.controller.ServletDispatcher.java
public void invokeControllerAction(String controllerName, String actionName, HttpServletRequest req, HttpServletResponse resp) throws IOException { String servletPath = ServletDispatcher.getServletPath(req); try {//from w ww.ja v a2s . com RequestManager manager = new RequestManager(req); Class<?> baseClass = LoaderDecorator.load(controllerName + "Base"); Method baseMethod = RequestScraper.getMethod(actionName, baseClass); if (baseMethod != null) { ActionParameters annotation = baseMethod.getAnnotation(ActionParameters.class); // POST methods cannot be invoked through GETS if (annotation.post() && servletMethod.equals(ServletMethod.GET)) { String msg = "The uri [" + servletPath + "] can only be accessed by a post method"; throw new IllegalURIMethodException(msg, req.getLocale(), servletPath); } else { dispatch(req, resp, manager, actionName, controllerName, baseClass, baseMethod); } } else { String msg = "A servlet at the uri [" + servletPath + "] does not exist."; throw new UnknownServletException(msg, req.getLocale(), servletPath); } } catch (RuntimeException ex) { if (ex instanceof LoaderDecoratorExceptionIF) { String msg = "A servlet at the uri [" + servletPath + "] does not exist."; throw new UnknownServletException(msg, req.getLocale(), servletPath); } else { throw ex; } } catch (NoSuchMethodException e) { String msg = "A servlet at the uri [" + servletPath + "] does not exist."; throw new UnknownServletException(msg, req.getLocale(), servletPath); } catch (InstantiationException e) { String msg = "A servlet at the uri [" + servletPath + "] does not exist."; throw new UnknownServletException(msg, req.getLocale(), servletPath); } catch (IllegalAccessException e) { String msg = "A servlet at the uri [" + servletPath + "] does not exist."; throw new UnknownServletException(msg, req.getLocale(), servletPath); } catch (InvocationTargetException e) { this.handleInvocationTargetException(e); } }