Example usage for javax.servlet.http HttpServletRequest getLocale

List of usage examples for javax.servlet.http HttpServletRequest getLocale

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getLocale.

Prototype

public Locale getLocale();

Source Link

Document

Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

Usage

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.StockBilletterieReservationApp.java

/**
 * Send request notification/*from   w w w.  j av  a 2  s.c  om*/
 *
 * @param bookingList the booking list
 * @param purchaser the purchaser
 * @param request the request
 * @return the notification dto
 */
private NotificationDTO sendRequestNotification(List<ReservationDTO> bookingList,
        UnauthentifiedPurchaserDTO purchaser, HttpServletRequest request) {
    //Generate mail content
    Map<String, Object> model = new HashMap<String, Object>();
    model.put(PARAMETER_BOOKING_LIST, bookingList);
    model.put(MARK_PURCHASER, purchaser);
    model.put(MARK_BASE_URL, AppPathService.getBaseUrl(request));
    model.put(PARAMETER_SEANCE_DATE, request.getParameter(PARAMETER_SEANCE_DATE));

    String showName = request.getParameter(PARAMETER_SHOW_NAME);
    model.put(PARAMETER_SHOW_NAME, showName);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_DIR + TEMPLATE_NOTIFICATION_REQUEST,
            request.getLocale(), model);

    // Create mail object
    NotificationDTO notificationDTO = new NotificationDTO();
    notificationDTO.setRecipientsTo(AppPropertiesService.getProperty(PROPERTY_NOTIFICATION_REQUEST_RECIPIENT));
    notificationDTO.setSubject(getMessage(MESSAGE_NOTIFICATION_REQUEST_SUBJECT, request, showName));
    notificationDTO.setMessage(template.getHtml());

    // Send it
    _notificationService.send(notificationDTO);

    return notificationDTO;
}

From source file:it.cilea.osd.jdyna.web.controller.ImportConfigurazione.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   www  . j  a v  a  2s  .  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() },
                getApplicationContext());

    } catch (XmlBeanDefinitionStoreException exc) {
        //cancello il file dalla directory temporanea
        logger.warn("Errore nell'importazione della configurazione dal 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.getBeanNamesForType(tpClass);
    //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 {
            TP tipologiaDaImportare = (TP) context.getBean(tpNameDefinition);
            applicationService.saveOrUpdate(tpClass, tipologiaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            j++;
            i--;
        }
        i++;
    }

    String[] areeDefinitions = context.getBeanNamesForType(areaClass);
    int w = 0;
    int v = 0;
    for (String areaNameDefinition : areeDefinitions) {
        try {
            A areaDaImportare = (A) context.getBean(areaNameDefinition);
            applicationService.saveOrUpdate(areaClass, areaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            v++;
            w--;
        }
        w++;
    }
    // check sulla tipologia poiche' ci sono oggetti che non hanno la tipologia tipo Opera e Parte
    if (typeClass != null) {
        String[] typeDefinitions = context.getBeanNamesForType(typeClass);
        int r = 0;
        int t = 0;
        for (String typeDefinition : typeDefinitions) {
            try {
                TY tipologiaDaImportare = (TY) context.getBean(typeDefinition);
                applicationService.saveOrUpdate(typeClass, tipologiaDaImportare);
            } catch (Exception ecc) {
                saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                        new Object[] { ecc.getMessage() }, request.getLocale()));
                t++;
                r--;
            }
            r++;
        }

        saveMessage(request,
                getText("action.file.success.upload.tipologie",
                        new Object[] { new String("Totale Tipologie:" + (t + r) + " [" + r
                                + "caricate con successo/" + t + " fallito caricamento]") },
                        request.getLocale()));

    }

    saveMessage(request,
            getText("action.file.success.upload",
                    new Object[] {
                            new String("Totale TP:" + (i + j) + "" + "[" + i + " caricate con successo/" + j
                                    + " fallito caricamento]"),
                            new String("Totale Aree:" + (w + v) + " [" + w + "caricate con successo/" + v
                                    + " fallito caricamento]") },
                    request.getLocale()));

    return new ModelAndView(getDetailsView());
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;//from   w  w w  . j a  va 2s . c o  m
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:fr.paris.lutece.plugins.extend.modules.rating.web.RatingJspBean.java

/**
 * Send notification./*from w w  w .  j  ava2 s  .  c o  m*/
 * @param request the request
 * @param strIdExtendableResource the str id extendable resource
 * @param strExtendableResourceType the str extendable resource type
 * @param nVoteValue the n vote value
 */
private void sendNotification(HttpServletRequest request, String strIdExtendableResource,
        String strExtendableResourceType, int nVoteValue) {
    RatingExtenderConfig config = _configService.find(RatingResourceExtender.RESOURCE_EXTENDER,
            strIdExtendableResource, strExtendableResourceType);
    int nMailingListId = config.getIdMailingList();
    Collection<Recipient> listRecipients = AdminMailingListService.getRecipients(nMailingListId);

    for (Recipient recipient : listRecipients) {
        Map<String, Object> model = new HashMap<String, Object>();

        String strSenderName = AppPropertiesService.getProperty(RatingConstants.PROPERTY_LUTECE_NAME);
        String strSenderEmail = AppPropertiesService.getProperty(RatingConstants.PROPERTY_WEBMASTER_EMAIL);
        String strResourceName = _resourceExtenderService.getExtendableResourceName(strIdExtendableResource,
                strExtendableResourceType);

        Object[] params = { strResourceName };
        String strSubject = I18nService.getLocalizedString(RatingConstants.MESSAGE_NOTIFY_SUBJECT, params,
                request.getLocale());

        model.put(RatingConstants.MARK_RESOURCE_EXTENDER_NAME, strResourceName);
        model.put(RatingConstants.MARK_VOTE_VALUE, nVoteValue);

        HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_RATING_NOTIFY_MESSAGE,
                request.getLocale(), model);
        String strBody = template.getHtml();

        MailService.sendMailHtml(recipient.getEmail(), strSenderName, strSenderEmail, strSubject, strBody);
    }
}

From source file:org.guanxi.idp.form.RegisterSPFormController.java

/**
 * Handles input from the web form to register a new SP
 *
 * @param request Standard issue HttpServletRequest
 * @param response Standard issue HttpServletResponse
 * @throws ServletException/*from  w w w.j  a  v a 2s  .co  m*/
 */
@SuppressWarnings("unchecked")
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException {

    RegisterSP form = (RegisterSP) command;

    IdpDocument.Idp idpConfig = (IdpDocument.Idp) getServletContext()
            .getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG);

    ServiceProvider sp = idpConfig.addNewServiceProvider();
    sp.setName(form.getProviderId());
    sp.setIdentity(form.getIdentity());
    sp.setCreds(form.getCreds());

    XmlOptions xmlOptions = new XmlOptions();
    xmlOptions.setSavePrettyPrint();
    xmlOptions.setSavePrettyPrintIndent(2);
    xmlOptions.setUseDefaultNamespace();

    IdpDocument idpDoc = (IdpDocument) getServletContext().getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG_DOC);
    try {
        idpDoc.save(new File(getServletContext().getRealPath("/WEB-INF/guanxi_idp/config/idp.xml")),
                xmlOptions);
    } catch (IOException ioe) {
    }

    getServletContext().setAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG, idpConfig);

    ModelAndView mAndV = new ModelAndView(getSuccessView(), errors.getModel());
    mAndV.getModel().put("message", messageSource.getMessage("register.sp.success.message",
            new Object[] { form.getProviderId() }, request.getLocale()));

    return mAndV;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java

@RequestMapping(value = "/upload_logo", method = RequestMethod.POST)
@ResponseBody//from w ww . java2  s .  co  m
public String uploadServiceInstanceLogo(@ModelAttribute("serviceInstanceLogoForm") ServiceInstanceLogoForm form,
        BindingResult result, HttpServletRequest request, ModelMap map) {

    logger.debug("### upload service instance logo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");

        return messageSource.getMessage(result.getFieldError("logo").getCode(), new Object[] { fileSize },
                request.getLocale());

    }
    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (StringUtils.isNotBlank(rootImageDir)) {
        ServiceInstance serviceInstance = form.getServiceInstance();
        ServiceInstanceLogoFormValidator validator = new ServiceInstanceLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale());
        } else {
            setImagePath(rootImageDir, serviceInstance, form.getLogo());
        }
        return "success";
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale());
    }
}

From source file:fr.paris.lutece.plugins.crm.modules.form.service.draft.CRMDraftBackupService.java

/**
 * {@inheritDoc}/*from  w w w .j av a  2  s . co  m*/
 */
@Override
public void validateDraft(HttpServletRequest request, Form form) {
    if (_logger.isDebugEnabled()) {
        _logger.debug("Validating Draft ...");
    }

    HttpSession session = request.getSession(true);

    String strKey = (String) session.getAttribute(Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS);
    String strDemandId = (String) session.getAttribute(Constants.SESSION_ATTRIBUTE_ID_DEMAND_PARAMS);
    String strCrmWebAppCode = (String) session
            .getAttribute(Constants.SESSION_ATTRIBUTE_DEMAND_CRM_WEBB_APP_CODE_PARAMS);

    if (StringUtils.isNotBlank(strKey)) {
        String strStatusText = I18nService.getLocalizedString(Constants.PROPERTY_CRM_STATUS_TEXT_VALIDATE,
                request.getLocale());

        try {
            _crmClientService.sendUpdateDemand(strDemandId, strStatusText, strCrmWebAppCode,
                    CrmClientConstants.CRM_STATUS_VALIDATED, strKey);

        } catch (CRMException e) {
            AppLogService.error(e);
        }
        byte[] dataForm = _blobStoreService.getBlob(strKey);

        if (dataForm != null) {
            String strDataForm = new String(dataForm);
            deleteFiles(strDataForm);
        }

        _blobStoreService.delete(strKey);

        // Remove session attributes
        removeSessionAttributes(session);

    }
}

From source file:fr.paris.lutece.plugins.mylutece.web.MyLuteceApp.java

/**
 * Build the Login page/*w  w w.  java 2  s  .  c om*/
 * @param page The XPage object to fill
 * @param request The HTTP request
 * @return The XPage object containing the page content
 */
private XPage getLoginPage(XPage page, HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();

    String strError = request.getParameter(PARAMETER_ERROR);
    String strErrorMessage = "";
    String strErrorDetail = "";

    if (strError != null) {
        if (strError.equals(PARAMETER_ERROR_VALUE_INVALID)) {
            strErrorMessage = AppPropertiesService.getProperty(PROPERTY_MYLUTECE_MESSAGE_INVALID_LOGIN);

            if (request.getParameter(PARAMETER_ERROR_MSG) != null) {
                strErrorDetail = request.getParameter(PARAMETER_ERROR_MSG);
            }
        } else if (strError.equals(PARAMETER_ERROR_CAPTCHA)) {
            strErrorMessage = I18nService.getLocalizedString(PROPERTY_MYLUTECE_MESSAGE_INVALID_CAPTCHA,
                    request.getLocale());
        }
    }

    HttpSession session = request.getSession(false);
    Boolean bEnableCaptcha = Boolean.FALSE;

    if (session != null) {
        bEnableCaptcha = (Boolean) session.getAttribute(PARAMETER_IS_ACTIVE_CAPTCHA);

        if (bEnableCaptcha == null) {
            bEnableCaptcha = Boolean.FALSE;
        }
    }

    model.put(MARK_ERROR_MESSAGE, strErrorMessage);
    model.put(MARK_ERROR_DETAIL, strErrorDetail);
    model.put(MARK_URL_DOLOGIN, getDoLoginUrl());
    model.put(MARK_AUTH_PROVIDER, request.getParameter(PARAMETER_AUTH_PROVIDER));
    model.put(MARK_IS_ACTIVE_CAPTCHA, bEnableCaptcha);

    if (bEnableCaptcha) {
        CaptchaSecurityService captchaService = new CaptchaSecurityService();
        model.put(MARK_CAPTCHA, captchaService.getHtmlCode());
    }

    model.put(SecurityTokenService.MARK_TOKEN,
            SecurityTokenService.getInstance().getToken(request, TOKEN_ACTION_LOGIN));

    HtmlTemplate template;
    model.put(MARK_URL_NEWACCOUNT,
            SecurityService.getInstance().getAuthenticationService().getNewAccountPageUrl());

    if (SecurityService.getInstance().isMultiAuthenticationSupported()) {
        LuteceAuthentication luteceAuthentication = SecurityService.getInstance().getAuthenticationService();

        if (luteceAuthentication instanceof MultiLuteceAuthentication) {
            model.put(MARK_LIST_AUTHENTICATIONS,
                    ((MultiLuteceAuthentication) luteceAuthentication).getListLuteceAuthentication());
        }

        template = AppTemplateService.getTemplate(TEMPLATE_LOGIN_MULTI_PAGE, _locale, model);
    } else {
        template = AppTemplateService.getTemplate(TEMPLATE_LOGIN_PAGE, _locale, model);
    }

    page.setContent(template.getHtml());
    page.setPathLabel(AppPropertiesService.getProperty(PROPERTY_MYLUTECE_PATHLABEL_LOGIN));
    page.setTitle(AppPropertiesService.getProperty(PROPERTY_MYLUTECE_PAGETITLE_LOGIN));

    return page;
}

From source file:fr.paris.lutece.plugins.directory.modules.rest.service.DirectoryRestService.java

/**
 * Gets the record fields list for the record.
 * @param request the request//from  w w w  . j  a v a2 s  . com
 * @param record the record
 * @return the record fields
 * @throws DirectoryErrorException if occurs
 */
private List<RecordField> getRecordFields(HttpServletRequest request, Record record)
        throws DirectoryErrorException {
    List<RecordField> listRecordFields = new ArrayList<RecordField>();
    EntryFilter filter = new EntryFilter();
    filter.setIdDirectory(record.getDirectory().getIdDirectory());
    filter.setIsComment(EntryFilter.FILTER_FALSE);
    filter.setIsEntryParentNull(EntryFilter.FILTER_TRUE);

    List<IEntry> listEntryFirstLevel = EntryHome.getEntryList(filter, getPlugin());

    for (IEntry entry : listEntryFirstLevel) {
        // no directory error testing (i.e. mandatory fields can be blanks)
        DirectoryUtils.getDirectoryRecordFieldData(record, request, entry.getIdEntry(), false, listRecordFields,
                getPlugin(), request.getLocale());
    }

    return listRecordFields;
}

From source file:psiprobe.controllers.DecoratorController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    try {/*from   w  w w. ja v  a2 s  . c  o  m*/
        request.setAttribute("hostname", InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        request.setAttribute("hostname", "unknown");
        logger.trace("", e);
    }

    Properties version = (Properties) getApplicationContext().getBean("version");
    request.setAttribute("version", version.getProperty("probe.version"));

    long uptimeStartValue = ManagementFactory.getRuntimeMXBean().getStartTime();
    long uptime = System.currentTimeMillis() - uptimeStartValue;
    long uptimeDays = uptime / (1000 * 60 * 60 * 24);

    uptime = uptime % (1000 * 60 * 60 * 24);
    long uptimeHours = uptime / (1000 * 60 * 60);

    uptime = uptime % (1000 * 60 * 60);
    long uptimeMins = uptime / (1000 * 60);

    request.setAttribute("uptime_days", uptimeDays);
    request.setAttribute("uptime_hours", uptimeHours);
    request.setAttribute("uptime_mins", uptimeMins);
    //
    // Work out the language of the interface by matching resource files that we have
    // to the request locale.
    //
    String lang = "en";
    for (String fileName : getMessageFileNamesForLocale(request.getLocale())) {
        if (getServletContext().getResource(fileName + ".properties") != null) {
            lang = fileName.substring(messagesBasename.length() + 1);
            break;
        }
    }

    request.setAttribute("lang", lang);

    return super.handleRequestInternal(request, response);
}