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.crm.modules.mylutece.web.CRMMyluteceJspBean.java

/**
 * Gets the manage my lutece users./* w  w w . ja  v a2 s .c  o  m*/
 *
 * @param request the request
 * @param response the response
 * @return the manage my lutece users
 * @throws AccessDeniedException the access denied exception
 */
public IPluginActionResult getManageMyLuteceUsers(HttpServletRequest request, HttpServletResponse response)
        throws AccessDeniedException {
    setPageTitleProperty(PROPERTY_MANAGE_CRM_USERS_PAGE_TITLE);

    Map<String, Object> model = new HashMap<String, Object>();
    _userSearchFields.fillModel(getUrlManageUsers(request, true).getUrl(), request, model);
    model.put(MARK_LIST_ATTRIBUTE_KEYS, _crmUserAttributesService.getUserAttributeKeys());

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_MANAGE_CRM_USERS, request.getLocale(),
            model);

    IPluginActionResult result = new DefaultPluginActionResult();

    result.setHtmlContent(getAdminPage(template.getHtml()));

    return result;
}

From source file:org.squale.squaleweb.applicationlayer.action.results.project.TopAction.java

/**
 * Exporte les tops au format PDF//  w  w w  . j a  v a  2s . c  om
 * 
 * @param mapping le actionMapping
 * @param form le form
 * @param request la request
 * @param response la response
 * @return l'actionForward
 * @throws ServletException exception pouvant etre levee
 */
public ActionForward exportToPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException {
    TopListForm theForm = (TopListForm) form;
    Collection data = theForm.getComponentListForm();
    try {
        HashMap parameters = new HashMap();
        PDFDataJasperReports pdfData = new PDFDataJasperReports(request.getLocale(), getResources(request),
                data, "/org/squale/squaleweb/resources/jasperreport/tops.jasper", false, parameters);

        // Le nom de la mtrique
        parameters.put("tre", WebMessages.getString(request, theForm.getTre()));
        // Le type de composant
        parameters.put("type", WebMessages.getString(request, theForm.getComponentType()));
        // Le nom de l'utilisateur
        LogonBean logon = (LogonBean) request.getSession().getAttribute(WConstants.USER_KEY);
        parameters.put("userName", logon.getMatricule());
        // Le nom de l'application
        parameters.put("applicationName", theForm.getApplicationName());
        // Le nom du projet
        parameters.put("projectName", theForm.getProjectName());
        // La date de l'audit
        parameters.put("auditDate", theForm.getAuditName());
        // La date de l'audit prcdent
        parameters.put("previousAuditDate", theForm.getPreviousAuditName());
        PDFFactory.generatePDFToHTTPResponse(pdfData, response, "", PDFEngine.JASPERREPORTS);
    } catch (Exception e) {
        throw new ServletException(e);
    }
    return null;
}

From source file:edu.cornell.mannlib.vitro.webapp.i18n.I18n.java

/**
 * Get an I18nBundle by this name. The request provides the preferred
 * Locale, the application directory, the theme directory and the
 * development mode flag./*from ww  w .ja  v  a  2s. co  m*/
 * 
 * If the request indicates that the system is in development mode, then the
 * cache is cleared on each request.
 * 
 * If the theme directory has changed, the cache is cleared.
 * 
 * Declared 'protected' so it can be overridden in unit tests.
 */
protected I18nBundle getBundle(String bundleName, HttpServletRequest req) {
    log.debug("Getting bundle '" + bundleName + "'");

    I18nLogger i18nLogger = new I18nLogger();
    try {
        checkDevelopmentMode(req);
        checkForChangeInThemeDirectory(req);

        String dir = themeDirectory.get();
        ServletContext ctx = req.getSession().getServletContext();

        ResourceBundle.Control control = new ThemeBasedControl(ctx, dir);
        ResourceBundle rb = ResourceBundle.getBundle(bundleName, req.getLocale(), control);
        return new I18nBundle(bundleName, rb, i18nLogger);
    } catch (MissingResourceException e) {
        log.warn("Didn't find text bundle '" + bundleName + "'");
        return I18nBundle.emptyBundle(bundleName, i18nLogger);
    } catch (Exception e) {
        log.error("Failed to create text bundle '" + bundleName + "'", e);
        return I18nBundle.emptyBundle(bundleName, i18nLogger);
    }
}

From source file:fr.paris.lutece.portal.web.PortalJspBean.java

/**
 * Do send a resource//from  w  w  w  . j  a  v a  2 s.com
 * @param request The request
 * @return The HTML content to display
 * @throws SiteMessageException If the resource or its associated service is
 *             not found
 */
public static String sendResource(HttpServletRequest request) throws SiteMessageException {
    String strSenderEmail = request.getParameter(PARAMETER_SENDER_EMAIL);
    String strSenderName = request.getParameter(PARAMETER_SENDER_NAME);
    String strSenderFirstName = request.getParameter(PARAMETER_SENDER_FIRST_NAME);
    String strReceipientEmail = request.getParameter(Parameters.EMAIL);
    String strContent = request.getParameter(PARAMETER_CONTENT);
    String strExtendableResourceType = request.getParameter(PARAMETER_EXTENDABLE_RESOURCE_TYPE);
    String strIdExtendableResource = request.getParameter(PARAMETER_ID_EXTENDABLE_RESOURCE);
    String strSend = request.getParameter(PARAMETER_SEND);
    IExtendableResource resource = null;

    String strError = null;

    // If the form was submited, we check data
    if (strSend != null) {
        if (StringUtils.isEmpty(strSenderEmail) || StringUtils.isEmpty(strSenderName)
                || StringUtils.isEmpty(strSenderFirstName) || StringUtils.isEmpty(strReceipientEmail)
                || StringUtils.isEmpty(strContent)) {
            strError = I18nService.getLocalizedString(MESSAGE_ERROR_MANDATORY_FIELDS, request.getLocale());
        }

        if ((strError != null) && (!AdminUserService.checkEmail(strSenderEmail)
                || !AdminUserService.checkEmail(strReceipientEmail))) {
            strError = I18nService.getLocalizedString(MESSAGE_ERROR_WRONG_SENDER_EMAIL, request.getLocale());
        }
    }

    // We get the resource from its resource service
    IExtendableResourceService resourceService = null;
    List<IExtendableResourceService> listExtendableResourceService = SpringContextService
            .getBeansOfType(IExtendableResourceService.class);

    for (IExtendableResourceService extendableResourceService : listExtendableResourceService) {
        if (extendableResourceService.isInvoked(strExtendableResourceType)) {
            resourceService = extendableResourceService;
            resource = extendableResourceService.getResource(strIdExtendableResource,
                    strExtendableResourceType);
        }
    }

    if ((resourceService == null) || (resource == null)) {
        SiteMessageService.setMessage(request, MESSAGE_NO_RESOURCE_FOUND, SiteMessage.TYPE_ERROR);
        throw new SiteMessageException();
    }

    String strResourceUrl = resourceService.getResourceUrl(strIdExtendableResource, strExtendableResourceType);
    Map<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_RESOURCE, resource);
    model.put(MARK_RESOURCE_URL, strResourceUrl);
    model.put(Markers.BASE_URL, AppPathService.getBaseUrl(request));

    if ((strSend != null) && (strError == null)) {
        Map<String, Object> mailModel = new HashMap<String, Object>();
        mailModel.put(Markers.BASE_URL, AppPathService.getBaseUrl(request));
        mailModel.put(MARK_RESOURCE, resource);
        mailModel.put(PARAMETER_SENDER_EMAIL, strSenderEmail);
        mailModel.put(PARAMETER_SENDER_NAME, strSenderName);
        mailModel.put(PARAMETER_SENDER_FIRST_NAME, strSenderFirstName);
        mailModel.put(Parameters.EMAIL, strReceipientEmail);
        mailModel.put(PARAMETER_CONTENT, EditorBbcodeService.getInstance().parse(strContent));
        mailModel.put(MARK_RESOURCE_URL,
                resourceService.getResourceUrl(strIdExtendableResource, strExtendableResourceType));

        HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_EMAIL_SEND_RESOURCE,
                request.getLocale(), mailModel);
        MailService.sendMailHtml(strReceipientEmail, strSenderFirstName + CONSTANT_SPACE + strSenderName,
                strSenderEmail, resource.getExtendableResourceName(), template.getHtml());
        model.put(MARK_SUCCESS, MARK_SUCCESS);
    } else {
        model.put(PARAMETER_SENDER_EMAIL, strSenderEmail);
        model.put(PARAMETER_SENDER_NAME, strSenderName);
        model.put(PARAMETER_SENDER_FIRST_NAME, strSenderFirstName);
        model.put(Parameters.EMAIL, strReceipientEmail);
        model.put(PARAMETER_CONTENT, strContent);
        model.put(MARK_ERROR, strError);
    }

    model.put(Markers.PAGE_MAIN_MENU, StringUtils.EMPTY);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_SEND_RESOURCE, request.getLocale(), model);

    return template.getHtml();
}

From source file:alpha.portal.webapp.controller.AdornmentFormController.java

/**
 * shows the adornment form.//from   w w  w  .  ja  v  a2 s.c  o m
 * 
 * @param request
 *            the request
 * @param model
 *            the model
 * @return a new adornment
 * @see adornmentform.jsp
 */
@RequestMapping(method = RequestMethod.GET)
protected String showForm(final HttpServletRequest request, final Model model) {
    final String adornmentId = request.getParameter("id");
    final String cardId = request.getParameter("card");
    final String caseId = request.getParameter("case");
    this.setCancelView("redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId);
    this.setSuccessView("redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId);
    this.setupAdornmentTypes(caseId, cardId);
    final Locale locale = request.getLocale();

    final List<ContributorRole> roles = this.contributorRoleManager.getAll();
    model.addAttribute("roles", roles);

    Adornment adornment = new Adornment();
    if (StringUtils.isNotEmpty(adornmentId)) {
        try {
            Long.valueOf(adornmentId);
        } catch (final NumberFormatException e) {
            this.saveError(request, this.getText("adornment.invalidId", locale));
            model.addAttribute("adornment", adornment);
            return "redirect:/adornmentform?id=" + adornmentId + "&card=" + cardId + "&case=" + caseId;
        }
        adornment = this.adornmentManager.get(Long.valueOf(adornmentId));
        final AdornmentType type = AdornmentType.fromName(adornment.getName());
        model.addAttribute("adornmentType", type);

    }

    final AlphaCard card = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId));
    final Adornment contributor = card.getAlphaCardDescriptor()
            .getAdornment(AdornmentType.Contributor.getName());

    if ((contributor.getValue() == null) || contributor.getValue().isEmpty()) {

        this.saveError(request, this.getText("adornment.noAccess", locale));
        return "redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId;

    } else {

        final Long contributorID = Long.parseLong(contributor.getValue());
        final User currentUser = this.getUserManager().getUserByUsername(request.getRemoteUser());

        if (contributorID != currentUser.getId()) {

            this.saveError(request, this.getText("adornment.noAccess", locale));
            return "redirect:/caseform?activeCardId=" + cardId + "&caseId=" + caseId;
        }
    }

    model.addAttribute("adornment", adornment);
    return null;
}

From source file:org.squale.squaleweb.applicationlayer.action.results.project.TopAction.java

/**
 * Exporte la liste des tops au format XLS
 * /*from www .j a  v  a  2 s. com*/
 * @param mapping le actionMapping
 * @param form le form
 * @param request la request
 * @param response la response
 * @return l'actionForward
 * @throws ServletException exception pouvant etre levee
 */
public ActionForward exportToExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException {
    // Le nom de l'utilisateur
    LogonBean logon = (LogonBean) request.getSession().getAttribute(WConstants.USER_KEY);
    try {
        // Il faut rcuprer les noms complets des composants
        ExcelDataTopList data = new ExcelDataTopList(request.getLocale(), getResources(request),
                (TopListForm) form, logon.getMatricule());
        ExcelFactory.generateExcelToHTTPResponse(data, response, "TopResults.xls");
    } catch (Exception e) {
        throw new ServletException(e);
    }
    return null;
}

From source file:org.squale.squaleweb.applicationlayer.action.results.project.TopAction.java

/**
 * Export components list to XLS format/*  www  .  j av  a2s  .c o  m*/
 * 
 * @param mapping mapping
 * @param form bean
 * @param request http request
 * @param response response
 * @return null (change http response header)
 * @throws ServletException if error
 */
public ActionForward exportComponentsToExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException {
    // user name
    LogonBean logon = (LogonBean) request.getSession().getAttribute(WConstants.USER_KEY);
    try {
        // we have to get full name of components
        ExcelDataComponentsResultsList data = new ExcelDataComponentsResultsList(request.getLocale(),
                getResources(request), (ComponentResultListForm) form, logon.getMatricule());
        ExcelFactory.generateExcelToHTTPResponse(data, response, "SQUALE_components.xls");
    } catch (ExcelGenerateurException ege) {
        throw new ServletException(ege);
    }
    return null;
}

From source file:org.guanxi.sp.engine.security.shibboleth.IdPVerifier.java

/**
 * Blocks access to an Engine's REST web service based on resident Engine metadata which defines what
 * entities can access that service./* w  ww.  j a va  2  s .  c om*/
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler
 * @return true if the caller is authorised to use the service
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    String idpProviderID = null;
    ResponseDocument responseDocument = null;
    ResponseType samlResponse = null;

    try {
        if (request.getParameter("SAMLResponse") == null) {
            logger.error("Could not process the AuthenticatonStatement from the IdP as there isn't one!");
            request.setAttribute("error",
                    messages.getMessage("engine.error.cannot.parse.authnstmnt", null, request.getLocale()));
            request.setAttribute("message",
                    messages.getMessage("engine.error.no.authn.stmnt", null, request.getLocale()));
            request.getRequestDispatcher(errorPage).forward(request, response);
            return false;
        }

        // Parse the SAML Response containing the AuthenticationStatement coming from the IdP
        responseDocument = ResponseDocument.Factory
                .parse(new StringReader(Utils.decodeBase64(request.getParameter("SAMLResponse"))));

        dumpSAML(responseDocument);

        samlResponse = responseDocument.getResponse();
        AssertionType assertion = samlResponse.getAssertionArray()[0];
        idpProviderID = assertion.getIssuer();
        AuthenticationStatementType authStatement = assertion.getAuthenticationStatementArray()[0];

        request.setAttribute(Config.REQUEST_ATTRIBUTE_SAML_RESPONSE, samlResponse);
        request.setAttribute(Config.REQUEST_ATTRIBUTE_IDP_PROVIDER_ID, idpProviderID);
        request.setAttribute(Config.REQUEST_ATTRIBUTE_IDP_NAME_IDENTIFIER,
                authStatement.getSubject().getNameIdentifier().getStringValue());
    } catch (Exception e) {
        logger.error("Could not process the AuthenticatonStatement from the IdP", e);
        request.setAttribute("error",
                messages.getMessage("engine.error.cannot.parse.authnstmnt", null, request.getLocale()));
        request.setAttribute("message", e.getMessage());
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    /* Find the IdP's metadata from our store. This is based on it's providerId, which is matched
     * against the entityID in the IdP's EntityDescriptor file.
     */
    EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_ENTITY_FARM);
    EntityManager manager = farm.getEntityManagerForID(idpProviderID);
    if (manager == null) {
        logger.error("Could not find manager for IdP '" + idpProviderID + "' in the metadata repository");
        request.setAttribute("error",
                messages.getMessage("engine.error.no.idp.metadata", null, request.getLocale()));
        request.setAttribute("message", idpProviderID);
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }
    if (manager.getMetadata(idpProviderID) != null) {
        // Apply the trust rules to the entity
        if (manager.getTrustEngine() != null) {
            if (manager.getTrustEngine().trustEntity(manager.getMetadata(idpProviderID), responseDocument)) {
                request.setAttribute(Config.REQUEST_ATTRIBUTE_IDP_METADATA, manager.getMetadata(idpProviderID));
            } else {
                logger.error("Trust failed for the IdP");
                request.setAttribute("error", messages.getMessage("engine.error.idp.sig.failed.verification",
                        null, request.getLocale()));
                request.setAttribute("message", idpProviderID);
                request.getRequestDispatcher(errorPage).forward(request, response);
                return false;
            }
        }
    } else {
        logger.error("Could not get IdP '" + idpProviderID + "' from the manager");
        request.setAttribute("error",
                messages.getMessage("engine.error.no.idp.metadata", null, request.getLocale()));
        request.setAttribute("message", idpProviderID);
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    return true;
}

From source file:it.cilea.osd.jdyna.web.controller.SimpleDynaController.java

protected ModelAndView handleDelete(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    String paramId = request.getParameter("id");
    Integer epiobjectID = Integer.valueOf(paramId);
    /* uso il delete controllato */
    AnagraficaSupport<P, TP> a = applicationService.get(objectClass, epiobjectID);

    try {/*from   ww  w .  ja  v  a 2 s . co  m*/
        applicationService.delete(objectClass, epiobjectID);
        saveMessage(request, getText(i18nPrefix + ".deleted", request.getLocale()));
    } catch (Exception e) {
        String path = Utils.getAdminSpecificPath(request, null);
        log.error("Non e' stato possibile eliminare l'oggetto " + e);
        saveMessage(request, getText(i18nPrefix + ".notdeleted", request.getLocale()));
        return new ModelAndView(getDetailsView() + "?id=" + epiobjectID + "&path=" + path, model);
    }

    return redirect(a, request);
}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public String getLanguageCode(HttpServletRequest req) {
    String cookieLoc = getCookieValue(req, LOCALE_COOKIE);
    Locale requestLocale = langutils.getProperLocale(req.getLocale().toString());
    return (cookieLoc != null) ? cookieLoc : requestLocale.getLanguage();
}