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:es.pode.administracion.presentacion.adminusuarios.bajaUsuario.BajaUsuarioControllerImpl.java

/**
 * @see es.pode.administracion.presentacion.adminusuarios.bajaUsuario.BajaUsuarioController#bajaUsuario(org.apache.struts.action.ActionMapping,
 *      es.pode.administracion.presentacion.adminusuarios.bajaUsuario.BajaUsuarioForm,
 *      javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///from w  w  w . j a  v a  2  s  .  co m
public final void bajaUsuario(ActionMapping mapping,
        es.pode.administracion.presentacion.adminusuarios.bajaUsuario.BajaUsuarioForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String listaId = request.getParameter("listaId");
    if (log.isDebugEnabled())
        log.debug("los ids de usuario que se quieren eliminar son " + listaId);
    Object[] objeto = listaId.split(" ");

    ResourceBundle ficheroRecursos = null;
    try {

        String login = LdapUserDetailsUtils.getLogin();
        SrvAdminUsuariosService srvAdminUsuariosService = this.getSrvAdminUsuariosService();
        UsuarioVO emailAdmin = srvAdminUsuariosService.obtenerDatosUsuario(login);
        ValidaBajaUsuarioVO validaBaja = srvAdminUsuariosService.bajaUsuario(obtenerIds(objeto), emailAdmin);
        Locale locale = request.getLocale();
        ficheroRecursos = this.getFicherRecursos(locale);
        form.setUsuariosDeleted(validaBaja.getItemsDeleted());
        form.setDescripcionBaja(ficheroRecursos.getString(validaBaja.getDescripcion()));
        form.setUsuariosDeleted(validaBaja.getItemsDeleted());

    } catch (Exception e) {
        log.error("Se ha producido un error al eliminar el usuario " + e);
        throw new ValidatorException("{errors.borrarUsuario}");
    }

}

From source file:es.pode.visualizador.presentacion.agregaSlider.AgregaSliderControllerImpl.java

/**
 * Metodo que construye el codigo html que el usuario debe copiar en su web para aadir
 * la galeria de imagenes/*from  w w  w. ja v  a  2s. c  o  m*/
 * 
 * @param mapping
 * @param form Formulario con los datos necesarios
 * @param request
 * @param response
 * @throws Exception
 */
public final void construirCodigo(ActionMapping mapping,
        es.pode.visualizador.presentacion.agregaSlider.ConstruirCodigoForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String keywords = form.getKeywords();
    String idioma = form.getIdiomasCombo();

    try {
        if (keywords == null || keywords == "") {
            //Lanzamos la excepcion porque las keywords estan vacias
            throw new ValidatorException("{agregaSlider.keywordVacia}");
        }

        boolean keywordsOK = comprobarKeywords(keywords);

        if (keywordsOK) {
            //Construimos el codigo html embebido
            String codigo = new String();

            ficheroRecursos = ResourceBundle.getBundle("application-resources", request.getLocale());

            String controller = ficheroRecursos.getString("agregaSlider.url.controller");
            String nodo = AgregaPropertiesImpl.getInstance().getProperty("host")
                    + AgregaPropertiesImpl.getInstance().getProperty("admin.ws.subdominio");

            String url = "http://" + nodo + "/" + ficheroRecursos.getString("agregaSlider.url.sfw");

            //rellenamos el codigo que le pasamos a la jsp para que el usuario lo recoja

            codigo = "<object width='400' height='400' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' "
                    + "codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"
                    + "<param name='movie' value='" + url + "' />" + "<param name='Flashvars' value='palabras="
                    + keywords + "&amp;idioma=" + idioma + "&amp;nodo=" + nodo + "&amp;controller=" + controller
                    + "' />" + "<param name='bgcolor' value='#FFFFFF' /> " + "<embed src='" + url + "' "
                    + "type='application/x-shockwave-flash' " + "Flashvars='palabras=" + keywords
                    + "&amp;idioma=" + idioma + "&amp;nodo=" + nodo + "&amp;controller=" + controller + "' "
                    + "bgcolor='#FFFFFF' " + "pluginspage='http://www.macromedia.com/go/getflashplayer'"
                    + "width='400' " + "height='400'>" + "</embed>" + "</object> ";

            form.setCodigo(codigo);
        } else
            //Lanzamos la excepcion porque alguna keywords no esta bien metida
            throw new ValidatorException("{agregaSlider.keywordIncorrecta}");

    } catch (ValidatorException Ve) {
        log.error("Ve ->" + Ve);
        throw Ve;
    } catch (Exception e) {
        log.error("Error al crear el codigo embebido para el agregaSlider: " + e);
        throw new ValidatorException("{agregaSilder.errorCrearCodigoEmbebido}");
    }

}

From source file:fr.paris.lutece.plugins.uploadimage.web.UploadimageApp.java

public String getMainUploadJs(HttpServletRequest request)

{

    String strFieldname = request.getParameter(PARAMATER_FIELDNAME);
    Options option;//w w  w.  j  av a  2 s.c o  m

    if (strFieldname != null && !strFieldname.isEmpty()) {
        option = OptionsHome.findByFieldName(strFieldname);
    } else {
        option = getDefaultOption();
    }
    if (option == null) {
        option = getDefaultOption();
    }

    Map<String, Object> model = new HashMap<>();
    model.put(MARK_BASE_URL, " strBaseUrl");
    model.put(MARK_OPTION, option);
    model.put(MARK_FIELDNAME, strFieldname);
    model.put(MARK_ERROR_MSG,
            I18nService.getLocalizedString("uploadimage.image.msg.error", request.getLocale()));

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

    return template.getHtml();

}

From source file:fr.paris.lutece.plugins.extend.modules.comment.web.CommentApp.java

/**
 * Gets the view comment page.//from  w  w  w.  j ava2  s.  com
 * 
 * @param request the request
 * @param strIdExtendableResource the str id extendable resource
 * @param strExtendableResourceType the str extendable resource type
 * @return the view comment page
 */
public XPage getViewCommentPage(HttpServletRequest request, String strIdExtendableResource,
        String strExtendableResourceType) {
    XPage page = new XPage();
    page.setTitle(I18nService.getLocalizedString(CommentConstants.PROPERTY_XPAGE_VIEW_COMMENTS_PAGE_TITLE,
            request.getLocale()));
    page.setPathLabel(I18nService.getLocalizedString(CommentConstants.PROPERTY_XPAGE_VIEW_COMMENTS_PATH_LABEL,
            request.getLocale()));

    page.setContent(getViewCommentPageContent(request, strIdExtendableResource, strExtendableResourceType,
            JSP_URL_DEFAULT_POST_BACK));
    return page;
}

From source file:org.guanxi.idp.service.AuthHandler.java

/**
 * Looks for an existing GuanxiPrincipal referenced by a request cookie. When a cookie is created after
 * a successful authentication at the IdP, either via the login page or an application cookie handler,
 * the corresponding GuanxiPrincipal is stored in the servlet context against the cookie value.
 * The new GuanxiPrincipal that is created after successful authentication is stored in the servlet
 * context under GuanxiPrincipal.id//  w w  w .jav a  2  s.  c  o  m
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler
 * @return true 
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    request.setCharacterEncoding("UTF-8");

    String missingParams = checkRequestParameters(request);
    if (missingParams != null) {
        logger.info("Missing param(s) : " + missingParams);
        request.setAttribute("message",
                messageSource.getMessage("missing.param", new Object[] { missingParams }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

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

    boolean spSupported = false;
    EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM);
    EntityManager manager = farm.getEntityManagerForID(request.getParameter(spIDRequestParam));
    if (manager != null) {
        SPMetadata metadata = (SPMetadata) manager.getMetadata(request.getParameter(spIDRequestParam));
        // Apply the trust rules to the SP
        if (metadata != null) {
            if (manager.getTrustEngine().trustEntity(metadata, request.getParameter("shire"))) {
                spSupported = true;
            } else {
                logger.error("Trust failure for " + request.getParameter(spIDRequestParam) + " --> "
                        + request.getParameter("shire"));
            }
        } else {
            logger.error("No Metadata Manager found for " + request.getParameter(spIDRequestParam));
        }
    } else {
        logger.error("No Metadata Manager");
    }

    // Check the locally registered SPs
    if (!spSupported) {
        ServiceProvider[] spList = idpConfig.getServiceProviderArray();
        for (int c = 0; c < spList.length; c++) {
            if (spList[c].getName().equals(request.getParameter(spIDRequestParam))) {
                // If it's in here, we trust it explicitly
                spSupported = true;
            }
        }
    }

    // Did we find the service provider?
    if (!spSupported) {
        logger.error(
                "Service Provider providerId " + request.getParameter(spIDRequestParam) + " not supported");
        request.setAttribute("message", messageSource.getMessage("sp.not.supported",
                new Object[] { request.getParameter(spIDRequestParam) }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                request.getRequestDispatcher(errorPage).forward(request, response);
                return false;
            }
        }
    }

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spIDRequestParam))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    request.getRequestDispatcher(authPage).forward(request, response);

    return false;
}

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

/**
 * Returns the code for the popup of the credits
 *
 * @param request The Http Request/*from w w w.  jav a 2s  .c  o  m*/
 * @return the html code for the popup credits
 */
public String getCredits(HttpServletRequest request) {
    HashMap<String, Object> model = new HashMap<String, Object>();
    fillPageModel(request, model);
    model.put(MARK_APP_VERSION, AppInfo.getVersion());
    model.put(MARK_PORTAL_DOMAIN, PortalService.getSiteName());
    model.put(Markers.PAGE_TITLE,
            I18nService.getLocalizedString(PROPERTY_PAGE_TITLE_CREDITS, request.getLocale()));

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

    return template.getHtml();
}

From source file:io.cfp.auth.api.LocalAuthController.java

/** Called whe a user submit a account creation form */
@RequestMapping(value = "/local/signup", method = RequestMethod.POST)
public String signup(HttpServletRequest request, @RequestParam @Log(USER) String email,
        @RequestParam(name = "g-recaptcha-response") String recaptcha, Map<String, Object> model) {

    if (!recaptchaService.isCaptchaValid(recaptcha)) {
        model.put("error", "invalidCaptcha");
        return signup(model);
    }/*  w  w w. j  a va2s  . c  o m*/

    logger.info("[LOCAL_REGISTERING] Registering user and send validation mail");
    User user = userService.findByemail(email);

    if (user == null) {
        user = new User();
        user.setEmail(email);
    }

    user.setVerifyToken(UUID.randomUUID().toString());
    userService.save(user);

    try {
        emailService.sendEmailValidation(user, request.getLocale());
    } catch (IOException e) {
        logger.error("[LOCAL_CONFIRM_MAIL_ERROR] Error when sending confirmation mail", e);
        model.put("error", "mailError");
        return signup(model);
    }

    logger.info("[LOCAL_VALIDATION] Validation mail successfully sent");
    return "redirect:/local/emailSent";
}

From source file:de.drv.dsrv.spoc.web.webservice.spring.SpocMessageDispatcherServlet.java

@Override
protected void doService(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    try {//from w  w  w.j  av  a  2  s . c o m
        if (LOG.isDebugEnabled()) {
            LOG.debug("Request eingegangen, Spring-WS-Verarbeitung wird aufgerufen.");
        }
        super.doService(request, response);
    } catch (final SaajSoapEnvelopeException ex) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Behandlung von Exception - exTRa-Error wird generiert: ", ex);
        }
        // Request enthaelt gueltiges XML, ist aber keine SOAP-Nachricht
        createExtraErrorAndWriteResponse(response, getWebApplicationContext()
                .getMessage(Messages.ERROR_REQUEST_NO_SOAP, null, request.getLocale()));
    }

    // Falls das XML im Request ungueltig ist, "verschluckt" der
    // WebServiceMessageReceiverHandlerAdapter
    // die Exception und setzt den HTTP Status auf 400.
    // Ganz sicher koennen wir hier aber nicht sein, ob das tatsaechlich die
    // Ursache ist.
    if (response.getStatus() == HttpServletResponse.SC_BAD_REQUEST) {
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("HTTP-Status 400 - exTRa-Error wird generiert.");
            }
            createExtraErrorAndWriteResponse(response, getWebApplicationContext()
                    .getMessage(Messages.ERROR_REQUEST_NO_XML, null, request.getLocale()));
        } catch (final Exception ignored) {
            // Evtl. kann nicht mehr in die Response geschrieben werden,
            // weil das vorher schon geschehen ist.
            LOG.warn("Exception beim Versuch, einen eigenen Extra-Error in die HttpResponse zu schreiben.",
                    ignored);
        }
    }
}

From source file:fr.paris.lutece.plugins.subscribe.web.SubscribeApp.java

/**
 * Get the HTML content to display the list of subscriptions of the current
 * user//from   ww  w .  j av a 2  s.  co m
 * @param request The user
 * @return The HTML content to display, or an empty string if the user has
 *         not logged in or if the authentication is not enabled
 */
public static String getSubscriptionList(HttpServletRequest request) {
    if (SecurityService.isAuthenticationEnable()) {
        LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);
        if (user != null) {
            SubscriptionService subscriptionService = SubscriptionService.getInstance();
            SubscriptionFilter filter = new SubscriptionFilter();
            filter.setIdSubscriber(user.getName());
            List<Subscription> listSubscription = subscriptionService.findByFilter(filter);
            List<SubscriptionDTO> listSubscriptionDto = new ArrayList<SubscriptionDTO>(listSubscription.size());
            for (Subscription subscription : listSubscription) {
                ISubscriptionProviderService providerService = subscriptionService
                        .getProviderService(subscription.getSubscriptionProvider());
                SubscriptionDTO subscriptionDTO = new SubscriptionDTO();
                subscriptionDTO.setIdSubscription(subscription.getIdSubscription());
                subscriptionDTO.setRemovable(providerService.isSubscriptionRemovable(user,
                        subscription.getSubscriptionKey(), subscription.getIdSubscribedResource()));
                subscriptionDTO.setUrlModify(providerService.getUrlModifySubscription(user,
                        subscription.getSubscriptionKey(), subscription.getIdSubscribedResource()));
                subscriptionDTO.setHtmlSubscription(providerService.getSubscriptionHtmlDescriptionBis(user,
                        subscription.getSubscriptionKey(), subscription.getIdSubscribedResource(),
                        request.getLocale(), subscription.getIdSubscribedResource()));
                listSubscriptionDto.add(subscriptionDTO);
            }

            Map<String, Object> model = new HashMap<String, Object>();
            model.put(MARK_LIST_SUBSCRIPTION_DTO, listSubscriptionDto);

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

            return template.getHtml();
        }
    }
    return StringUtils.EMPTY;
}