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:net.testdriven.psiprobe.controllers.DecoratorController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {//from  www .j  av a2s.  co  m
        request.setAttribute("hostname", InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        request.setAttribute("hostname", "unknown");
    }

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

    Object uptimeStart = getServletContext().getAttribute(UptimeListener.START_TIME_KEY);
    if (uptimeStart != null && uptimeStart instanceof Long) {
        long l = (Long) uptimeStart;
        long uptime = System.currentTimeMillis() - l;
        long uptime_days = uptime / (1000 * 60 * 60 * 24);

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

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

        request.setAttribute("uptime_days", uptime_days);
        request.setAttribute("uptime_hours", uptime_hours);
        request.setAttribute("uptime_mins", uptime_mins);
    }

    //
    // Work out the language of the interface by matching resource files that we have
    // to the request locale.
    //
    List fileNames = getMessageFileNamesForLocale(request.getLocale());
    String lang = "en";
    for (Object fileName : fileNames) {
        String f = (String) fileName;
        if (getServletContext().getResource(f + ".properties") != null) {
            lang = f.substring(messagesBasename.length() + 1);
            break;
        }
    }

    request.setAttribute("lang", lang);

    return super.handleRequestInternal(request, response);
}

From source file:mx.edu.um.mateo.general.web.BaseController.java

protected void enviaCorreo(String tipo, List<?> lista, HttpServletRequest request, String nombre,
        String tipoReporte, Long id) throws ReporteException {
    try {/*w  w w.  j  a va  2 s.com*/
        log.debug("Enviando correo {}", tipo);
        byte[] archivo = null;
        String tipoContenido = null;
        switch (tipo) {
        case "PDF":
            archivo = generaPdf(lista, nombre, tipoReporte, id);
            tipoContenido = "application/pdf";
            break;
        case "CSV":
            archivo = generaCsv(lista, nombre, tipoReporte, id);
            tipoContenido = "text/csv";
            break;
        case "XLS":
            archivo = generaXls(lista, nombre, tipoReporte, id);
            tipoContenido = "application/vnd.ms-excel";
        }

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(ambiente.obtieneUsuario().getCorreo());
        String titulo = messageSource.getMessage(nombre + ".reporte.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);
    } catch (JRException | MessagingException e) {
        throw new ReporteException("No se pudo generar el reporte", e);
    }
}

From source file:fr.paris.lutece.plugins.graphite.web.Graphite.java

/**
 * Returns the content of the page Graphite.
 * @param request The HTTP request//from  w  ww .j a v a2s  .c om
 * @return The view
 */
@View(value = VIEW_HOME, defaultView = true)
public XPage viewHome(HttpServletRequest request) {

    String strIdCategory = request.getParameter("category");
    int nId = -1;

    if (!StringUtils.isEmpty(strIdCategory)) {
        nId = Integer.parseInt(strIdCategory);
    } else {
        //default category
        List<Category> listCategorys = getAuthorizedCategory(request);
        if (!CollectionUtils.isEmpty(listCategorys)) {
            boolean find = false;
            for (Category c : listCategorys) {
                if (find == false) {
                    if (c.getDisplayFront() == 1) {
                        nId = c.getIdCategory();
                        find = true;
                    }
                }
            }
            if (find == false) {
                nId = listCategorys.get(0).getIdCategory();
            }
        }
    }

    Map<String, Object> model = getModel();

    if (nId != -1) {
        _category = CategoryHome.findByPrimaryKey(nId);

        model.put(MARK_CATEGORY, _category);
        model.put(MARKER_GRAPHS_LIST, GraphHome.getGraphsList());
        model.put(MARK_CATEGORIES_COMBO, getAuthorizedCategory(request));
        model.put(MARKER_ROLE, isAuthorized(request, _category));
    }

    return getXPage(TEMPLATE_XPAGE, request.getLocale(), model);
}

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

/**
 * Restore a draft/* w w  w  . ja va  2 s . c  o m*/
 * @param request the HTTP request
 */
private void restore(HttpServletRequest request) {
    if (_logger.isDebugEnabled()) {
        _logger.debug("Restoring Draft ...");
    }

    HttpSession session = request.getSession(true);

    String strData = ((String) session.getAttribute(Constants.SESSION_ATTRIBUTE_DEMAND_DATA_PARAMS));

    if (StringUtils.isNotBlank(strData)) {
        byte[] dataForm = _blobStoreService.getBlob(strData);

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

            if (StringUtils.isNotBlank(strDataForm)) {
                // bind responses to session if jsonresponse has content - use default otherwise.
                Map<Integer, List<Response>> mapResponses = JSONUtils.buildListResponses(strDataForm,
                        request.getLocale(), session);

                if (mapResponses != null) {
                    if (_logger.isDebugEnabled()) {
                        _logger.debug("Found reponses - restoring form");
                    }

                    FormUtils.restoreResponses(session, mapResponses);

                    for (Entry<Integer, List<Response>> entryMap : mapResponses.entrySet()) {
                        int nIdEntry = entryMap.getKey();
                        List<String> listBlobIds = JSONUtils.getBlobIds(strDataForm, nIdEntry);

                        if ((listBlobIds != null) && !listBlobIds.isEmpty()) {
                            for (String strBlobId : listBlobIds) {
                                FileItem fileItem;

                                try {
                                    fileItem = new BlobStoreFileItem(strBlobId, _blobStoreService);

                                    FormAsynchronousUploadHandler.getHandler().addFileItemToUploadedFilesList(
                                            fileItem,
                                            IEntryTypeService.PREFIX_ATTRIBUTE + Integer.toString(nIdEntry),
                                            request);

                                } catch (NoSuchBlobException nsbe) {
                                    // file might be deleted
                                    _logger.debug(nsbe.getMessage());
                                } catch (Exception e) {
                                    throw new AppException("Unable to parse JSON file metadata for blob id "
                                            + strBlobId + " : " + e.getMessage(), e);
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        AppLogService.error("No blob id found for the current session");
    }
}

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

/**
 * Get the manage purchases page/*from   w ww .j a  v a  2s . c  o m*/
 *
 * @param request the request
 * @return the page with purchases list
 */
public String getManagePurchases(HttpServletRequest request) {
    setPageTitleProperty(PROPERTY_PAGE_TITLE_MANAGE_PURCHASE);

    Map<String, Object> model = new HashMap<String, Object>();
    ReservationFilter filter = getPurchaseFilter(request);

    // if date begin is after date end, add error
    List<String> error = new ArrayList<String>();

    if ((filter.getDateBeginOffer() != null) && (filter.getDateEndOffer() != null)
            && filter.getDateBeginOffer().after(filter.getDateEndOffer())) {
        error.add(I18nService.getLocalizedString(MESSAGE_SEARCH_OFFER_DATE, request.getLocale()));
    }

    if ((filter.getDateBegin() != null) && (filter.getDateEnd() != null)
            && filter.getDateBegin().after(filter.getDateEnd())) {
        error.add(I18nService.getLocalizedString(MESSAGE_SEARCH_PURCHASE_DATE, request.getLocale()));
    }

    model.put(MARK_ERRORS, error);

    // OrderList for purchase list
    List<String> orderList = new ArrayList<String>();
    orderList.add(ORDER_FILTER_DATE);
    orderList.add(ORDER_FILTER_OFFER_PRODUCT_NAME);
    orderList.add(ORDER_FILTER_OFFER_DATE);
    orderList.add(ORDER_FILTER_OFFER_TYPE_NAME);
    filter.setOrders(orderList);
    filter.setOrderAsc(true);

    String strOfferId = request.getParameter(MARK_OFFER_ID);
    String purchaseId = request.getParameter(MARK_PURCHASSE_ID);

    if (strOfferId != null) {
        SeanceDTO seance = this._serviceOffer.findSeanceById(Integer.parseInt(strOfferId));

        if (StringUtils.isNotEmpty(purchaseId) && NumberUtils.validateInt(purchaseId)) {
            ReservationDTO reservation = this._servicePurchase.findById(Integer.parseInt(purchaseId));
            filter.setUserName(reservation.getUserName());
        }

        filter.setIdOffer(seance.getId());
        filter.setProductName(seance.getProduct().getName());
        filter.setIdGenre(seance.getIdGenre());
        filter.setDateBeginOffer(DateUtils.getDate(seance.getDate(), false));
        filter.setDateEndOffer(DateUtils.getDate(seance.getDate(), false));
    }

    //Obtention des objets sauvegards en session
    DataTableManager<ReservationDTO> dataTableToUse = getDataTable(request, filter);
    model.put(MARK_DATA_TABLE_PURCHASE, dataTableToUse);

    // Fill the model
    model.put(MARK_LOCALE, getLocale());

    // Combo
    ReferenceList offerGenreComboList = ListUtils.toReferenceList(_serviceOffer.findAllGenre(),
            BilletterieConstants.ID, BilletterieConstants.NAME, StockConstants.EMPTY_STRING);
    model.put(MARK_LIST_OFFER_GENRE, offerGenreComboList);
    // offer statut cancel
    model.put(MARK_PURCHASE_STATUT_CANCEL, TicketsConstants.OFFER_STATUT_CANCEL);
    // the filter
    model.put(TicketsConstants.MARK_FILTER, filter);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_MANAGE_PURCHASES, getLocale(), model);
    //opration ncessaire pour eviter les fuites de mmoires
    dataTableToUse.clearItems();

    return getAdminPage(template.getHtml());
}

From source file:it.cilea.osd.jdyna.controller.DecoratorPropertiesDefinitionController.java

protected ModelAndView handleDelete(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    String paramOTipologiaProprietaId = request.getParameter("pDId");
    String boxId = request.getParameter("boxId");
    String tabId = request.getParameter("tabId");
    Integer tipologiaProprietaId = Integer.decode(paramOTipologiaProprietaId);

    try {/*from   w ww  .  j a  v a2 s .co m*/

        TP tip = applicationService.get(targetModel, tipologiaProprietaId);

        //cancello tutte le proprieta' salvate in passato
        applicationService.<it.cilea.osd.jdyna.model.Property<TP>, TP>deleteAllProprietaByTipologiaProprieta(
                tip.getPropertyHolderClass(), tip);
        //cancello se fanno parte di qualche property holder      
        IContainable containable = applicationService.findContainableByDecorable(tip.getDecoratorClass(),
                tipologiaProprietaId);
        applicationService.<H, T>deleteContainableInPropertyHolder(holderModel, containable);
        if (TypedBox.class.isAssignableFrom(holderModel)) {
            TypedBox box = (TypedBox) applicationService.get(holderModel, Integer.parseInt(boxId));
            box.getTypeDef().getMask().remove(tip);
        }

        applicationService.delete(tip.getDecoratorClass(), containable.getId());

        saveMessage(request, getText("action.propertiesdefinition.deleted", request.getLocale()));
    } catch (Exception ecc) {
        saveMessage(request, getText("action.propertiesdefinition.deleted.noSuccess", request.getLocale()));
    }

    return new ModelAndView(getListView() + "?id=" + boxId + "&tabId=" + tabId + "&path="
            + Utils.getAdminSpecificPath(request, null), model);
}

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

/**
 * Does the logging out. The method looks for the user's IdP cookie in the
 * request and if it finds it, it extracts the corresponding GuanxiPrincipal
 * and sends it to SSO.logout() for processing.
 * /*from   www  . ja  va2s .  c om*/
 * @param request
 *          Standard HttpServletRequest
 * @param response
 *          Standard HttpServletRequest
 * @throws ServletException
 *           if an error occurrs
 * @throws IOException
 *           if an error occurrs
 */
public void processLogout(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String cookieName = getCookieName();
    boolean loggedOut = false;
    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...
                GuanxiPrincipal principal = (GuanxiPrincipal) servletContext
                        .getAttribute(cookies[c].getValue());

                // ...and get rid of it
                if (principal != null) {
                    servletContext.setAttribute(principal.getUniqueId(), null);
                }

                loggedOut = true;
            }
        }
    }

    /*
     * Only display the logout page if we're not in passive mode. What this
     * means is if we're in passive mode (passive = yes) then we're most likely
     * embedded in an application, which has it's own logout page.
     */
    if (!passive) {
        if (loggedOut)
            request.setAttribute("LOGOUT_MESSAGE",
                    messageSource.getMessage("idp.logout.successful", null, request.getLocale()));
        else
            request.setAttribute("LOGOUT_MESSAGE",
                    messageSource.getMessage("idp.logout.unsuccessful", null, request.getLocale()));

        request.getRequestDispatcher(logoutPage).forward(request, response);
    }
}

From source file:fr.paris.lutece.plugins.pluginwizard.web.PluginWizardApp.java

/**
 * The creation screen of a portlet//from  www.j a  v  a2s  .  com
 *
 * @param request The Http Request
 * @return The XPage
 */
@View(VIEW_CREATE_PORTLET)
public XPage getCreatePortlet(HttpServletRequest request) {
    _portlet = (_portlet != null) ? _portlet : new Portlet();

    Map<String, Object> model = getPluginModel();
    model.put(MARK_PORTLET, _portlet);

    return getXPage(TEMPLATE_CREATE_PLUGIN_PORTLET, request.getLocale(), model);
}

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

/**
 * Return html code for error message.//from  w w w  .j av  a 2s.c  o  m
 *
 * @param e the e
 * @param request the request
 * @return html
 */
protected String getHtmlError(FunctionnalException e, HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    List<String> messageList = new ArrayList<String>();

    try {
        throw e;
    }

    // Validation error
    catch (ValidationException ve) {
        String typeName = ve.getBean().getClass().getSimpleName();

        // Add a validation error message using value, field name and
        // provided
        // message
        for (ConstraintViolation<?> constraintViolation : ve.getConstraintViolationList()) {
            String fieldName = getMessage(
                    FIELD_MESSAGE_PREFIX + typeName + "." + constraintViolation.getPropertyPath(), request);
            messageList.add(getMessage(ERROR_MESSAGE_KEY, request,
                    String.valueOf(constraintViolation.getInvalidValue()), fieldName,
                    constraintViolation.getMessage()));
        }
    }

    // Business error
    catch (BusinessException be) {
        messageList.add(getMessage(be.getCode(), request, be.getArguments()));
    }

    model.put(MARK_MESSAGE_LIST, messageList);

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

    return template.getHtml();
}