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:org.jamwiki.servlets.TranslationServlet.java

/**
 * If a language is specified in the form, use it, other default to default language or
 * request language if no default is available.
 *///  ww w  .ja va  2  s  .c om
private String retrieveLanguage(HttpServletRequest request) {
    String language = request.getParameter("language");
    if (StringUtils.isBlank(language)) {
        WikiUser user = ServletUtil.currentWikiUser();
        if (!StringUtils.isBlank(user.getDefaultLocale())) {
            language = user.getDefaultLocale().split("_")[0];
        } else if (request.getLocale() != null) {
            language = request.getLocale().getLanguage();
        } else {
            language = "en";
        }
    }
    return language;
}

From source file:es.pode.administracion.presentacion.planificador.informeTrabajo.InformeControllerImpl.java

public final void obtenerInformeTrabajo(ActionMapping mapping, ObtenerInformeTrabajoForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {/*from www.  j  a v a 2s . c om*/
        Long informe = null;

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

        if (form instanceof InformeFormImpl)
            informe = ((InformeFormImpl) form).getId();
        else
            informe = ((MostrarDescripcionVolverFormImpl) form).getId();

        RegistroTareaEjecutadaVO[] informeTrabajo = this.getSrvPlanificadorService()
                .obtenerInformeTrabajo(informe);

        RegistroTareaEjecutadaDate[] registroTareasDate = null;

        if (informeTrabajo != null) {
            registroTareasDate = cambiarFormatoRegistroTareas(informeTrabajo, informe);
            form.setInformeTrabajoAsArray(registroTareasDate);
        }

        /* Cabecera del informe */
        TareaEjecutadaVO cabecera = this.getSrvPlanificadorService().obtenerTrabajoEjecutado(informe);

        /**
            * Recortamos el nombre de la tarea quitandole lo agregado al
            * nombre original Lo agregado son dos # seguidas de la fecha en
            * la que se ejecuta la tarea La fecha se compone de
            * "ao+mes+dia+hora+minutos+segundos"
            */
        int posicion = cabecera.getTrabajo().indexOf("!!");

        if (posicion > 0)
            form.setTrabajo(cabecera.getTrabajo().substring(0, posicion));
        else
            form.setTrabajo(cabecera.getTrabajo());

        form.setDescripcion(cabecera.getDescripcion());

        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy, HH:mm");

        if (log.isDebugEnabled())
            log.debug("cabecera.getFechaInicio()" + cabecera.getFechaInicio());
        String fechaInicio = formato.format(cabecera.getFechaInicio().getTime());
        form.setFechaInicio(fechaInicio);
        //log("fecha inicio despues del set" + form.getFechaInicio());

        if (cabecera.getFechaFin() != null)
            form.setFechaFin(formato.format(cabecera.getFechaFin().getTime()));

    } catch (Exception e) {
        log.error("Error: " + e);
        throw new ValidatorException("{tareas.error}");
    }
}

From source file:com.adeptj.runtime.servlet.ToolsServlet.java

/**
 * Renders tools page./*from  w  ww  .j a v  a  2  s  .c  om*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles();
    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    TemplateEngine.getInstance()
            .render(TemplateContext.builder().request(req).response(resp).template(TOOLS_TEMPLATE)
                    .locale(req.getLocale())
                    .templateData(TemplateData.newTemplateData().put("username", req.getRemoteUser())
                            .put("sysProps", System.getProperties().entrySet())
                            .put("totalBundles", bundles.length).put("bundles", bundles)
                            .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")")
                            .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")")
                            .put("startTime", Date.from(Instant.ofEpochMilli(startTime)))
                            .put("upTime", Times.format(startTime))
                            .put("maxMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getMax()))
                            .put("usedMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getUsed()))
                            .put("processors", Runtime.getRuntime().availableProcessors()))
                    .build());
}

From source file:es.pode.administracion.presentacion.nodos.altaNodo.AltaNodoControllerImpl.java

public void obtenerCCAA(ActionMapping mapping, ObtenerCCAAForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    try {/*from ww  w.j  a v  a 2s . c  om*/
        //recogemos las ccaa de la bbdd y las internacionalizamos desde el properties
        Locale locale = new Locale(LdapUserDetailsUtils.getIdioma());
        ficheroRecursos = ResourceBundle.getBundle("application-resources", request.getLocale());

        List ccaa = Arrays.asList(this.getSrvNodoService().obtenerCCAAs());
        CcaaVO[] ccaaVOArray = (CcaaVO[]) ccaa.toArray();
        List ccaaList = new ArrayList();
        for (int i = 0; i < ccaaVOArray.length; i++) {
            if (ccaaVOArray[i].getCodigo() != null) {
                String descripcion = null;
                try {
                    descripcion = ficheroRecursos.getString(ccaaVOArray[i].getCodigo());
                } catch (Exception ex) {
                    log.warn("El codigo de la comunidad " + ccaaVOArray[i].getCodigo()
                            + " no esta en el fichero de internacionalizacion");
                    descripcion = ccaaVOArray[i].getDescripcion();
                }
                ccaaList.add(descripcion.toLowerCase());
                ccaaVOArray[i].setDescripcion(descripcion);
            } else
                ccaaVOArray[i].setCodigo("");

        }
        Collections.sort(ccaaList);
        ccaa = ordenarLista(ccaaList, ccaaVOArray);

        // Rellena el combo de ccaa
        ((AltaNodoFormImpl) form).setCcaaBackingList(ccaa, "id", "descripcion");

    } catch (Exception e) {
        log.error("Error: " + e);
        throw new ValidatorException("{errors.altanodo}");
    }
}

From source file:es.pode.administracion.presentacion.planificador.listarTareasEjecutadas.TareasEjecutadasControllerImpl.java

/**
 * metodo que obtiene los trabajos que ya estan ejecutados
 *//*from w  ww .  j a  va 2  s.  c  o  m*/
public final void obtenerTrabajosEjecutados(ActionMapping mapping, ObtenerTrabajosEjecutadosForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
        Utiles utilidades = new Utiles();

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

        TareaEjecutadaVO[] tareas = this.getSrvPlanificadorService().obtenerTrabajosEjecutados();

        TareaEjecutadaDate[] tareasDate = null;

        if (tareas != null) {
            tareasDate = cambiarFormatoTareas(tareas);
            tareasDate = ordenaDescendente(tareasDate);
            ((ListarTareasEjecutadasFormImpl) form).setTareasEjecutadasAsArray(tareasDate);
        }

    } catch (Exception e) {
        log.error("Error: " + e);
        throw new ValidatorException("{tareas.error}");
    }
}

From source file:com.criticalsoftware.mobics.presentation.extension.DefaultExceptionHandler.java

/**
 * Return the action bean page with errors displayed
 * /*from   w ww . ja  v  a2 s.  c om*/
 * @param resourceKey
 * @param request
 * @param response
 * @return
 */
private Resolution insideJob(String resourceKey, HttpServletRequest request, HttpServletResponse response) {
    resources = ResourceBundle.getBundle("StripesResources", request.getLocale());
    ActionBean bean = (ActionBean) request.getAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN);
    Resolution resolution;
    if (bean != null && StringUtils.isNotBlank(bean.getContext().getSourcePage())) {
        bean.getContext().getValidationErrors().addGlobalError(new LocalizableError(resourceKey));
        resolution = new ForwardResolution(bean.getContext().getSourcePage());
    } else {
        request.setAttribute("error", resources.getString(resourceKey));
        resolution = new ForwardResolution(ErrorActionBean.class);
    }

    return resolution;
}

From source file:net.sf.appstatus.web.pages.StatusPage.java

public void doGetHTML(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
        throws UnsupportedEncodingException, IOException {

    setup(resp, "text/html");
    ServletOutputStream os = resp.getOutputStream();

    Map<String, String> valuesMap = new HashMap<String, String>();
    List<ICheckResult> results = webHandler.getAppStatus().checkAll(req.getLocale());
    Collections.sort(results);//ww  w .ja  va2  s.co  m
    boolean statusOk = true;
    int statusCode = 200;
    for (ICheckResult r : results) {
        if (r.getCode() != ICheckResult.OK && r.isFatal()) {
            resp.setStatus(500);
            statusCode = 500;
            statusOk = false;
            break;
        }
    }

    valuesMap.put("statusOk", String.valueOf(statusOk));
    valuesMap.put("statusCode", String.valueOf(statusCode));

    // STATUS TABLE
    StrBuilder sbStatusTable = new StrBuilder();
    if (HtmlUtils.generateBeginTable(sbStatusTable, results.size())) {

        HtmlUtils.generateHeaders(sbStatusTable, "", "Group", "Name", "Description", "Code", "Resolution");

        for (ICheckResult r : results) {
            HtmlUtils.generateRow(sbStatusTable, getStatus(r), r.getGroup(), r.getProbeName(),
                    r.getDescription(), String.valueOf(r.getCode()), r.getResolutionSteps());
        }
        HtmlUtils.generateEndTable(sbStatusTable, results.size());
    }
    valuesMap.put("statusTable", sbStatusTable.toString());

    // PROPERTIES TABLE
    StrBuilder sbPropertiesTable = new StrBuilder();
    Map<String, Map<String, String>> properties = webHandler.getAppStatus().getProperties();
    if (HtmlUtils.generateBeginTable(sbPropertiesTable, properties.size())) {

        HtmlUtils.generateHeaders(sbPropertiesTable, "", "Group", "Name", "Value");

        for (Entry<String, Map<String, String>> cat : properties.entrySet()) {
            String category = cat.getKey();

            for (Entry<String, String> r : cat.getValue().entrySet()) {
                HtmlUtils.generateRow(sbPropertiesTable, Resources.STATUS_PROP, category, r.getKey(),
                        r.getValue());
            }

        }
        HtmlUtils.generateEndTable(sbPropertiesTable, properties.size());
    }
    valuesMap.put("propertiesTable", sbPropertiesTable.toString());
    String content = HtmlUtils.applyLayout(valuesMap, PAGECONTENTLAYOUT);

    valuesMap.clear();
    valuesMap.put("content", content);
    os.write(getPage(webHandler, valuesMap).getBytes(ENCODING));
}

From source file:com.criticalsoftware.mobics.presentation.extension.DefaultExceptionHandler.java

/**
 * Return the error page with errors displayed
 * //  w ww.  jav  a  2  s  . co  m
 * @param resourceKey
 * @param request
 * @param response
 * @return
 */
private Resolution insideJobToError(String resourceKey, HttpServletRequest request,
        HttpServletResponse response) {
    resources = ResourceBundle.getBundle("StripesResources", request.getLocale());
    request.setAttribute("error", resources.getString(resourceKey));
    return new ForwardResolution(ErrorActionBean.class);
}

From source file:fr.paris.lutece.plugins.crm.service.demand.DemandTypeService.java

/**
 * Find the list of demand types for the lutece user ordered by id category
 * @param request {@link HttpServletRequest}
 * @return a map of (id_category, List&lt;DemandType&gt;)
 *//*from   ww  w  . j  ava2s .co  m*/
public Map<String, List<DemandType>> findForLuteceUser(HttpServletRequest request) {
    Map<String, List<DemandType>> map = new HashMap<String, List<DemandType>>();

    ReferenceList refListCategories = CategoryService.getService().getCategories(request.getLocale(), false,
            true);
    if (!CollectionUtils.isEmpty(refListCategories)) {
        for (ReferenceItem category : refListCategories) {
            int nIdCategory = Integer.parseInt(category.getCode());
            map.put(category.getCode(), findForLuteceUser(request, nIdCategory));
        }
    }

    return map;
}

From source file:org.shredzone.cilla.view.SearchView.java

/**
 * Shows the view result page.//from   w w w. ja  va 2  s  .  co  m
 */
@Framed
@View(pattern = "/search", name = "search")
@View(pattern = "/search/${date}", name = "search")
public String searchView(HttpServletRequest req, @Optional @PathPart("date") DateRange date,
        @Optional @Parameter("p") PaginatorModel paginator, @Optional @Parameter("q") String query)
        throws ViewException {
    if (query == null) {
        return "view/search.jsp";
    }

    if (query.trim().isEmpty()) {
        req.setAttribute("message", "search.msg.noterm");
        return "view/search.jsp";
    }

    Locale locale = req.getLocale();
    if (locale == null) {
        locale = Locale.ENGLISH;
    }

    if (paginator == null) {
        paginator = new PaginatorModel();
    }
    paginator.setPerPage(maxEntries);

    FilterModel filter = new FilterModel();
    filter.setLocale(locale);
    filter.setQuery(query);

    try {
        SearchResult result = searchService.search(filter);
        paginator.setCount(result.getCount());
        result.setPaginator(paginator);
        req.setAttribute("result", result);
    } catch (CillaServiceException ex) {
        req.setAttribute("message", "search.msg.failed");
        req.setAttribute("details", ex.getCause().getLocalizedMessage());
    }

    req.setAttribute("paginator", paginator);
    req.setAttribute("query", query);

    return "view/search.jsp";
}