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.planificador.eliminarTrabajoEjecutado.EliminarTrabajoControllerImpl.java

/**
 * metodo que elimina los trabajos seleccionados
 *///from w  w  w  .j  a v a2 s.  co m
public final void eliminarTrabajoEjecutado(ActionMapping mapping, EliminarTrabajoEjecutadoForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    Long[] trabajosIDs = null;
    Boolean resultado;
    String resultadoString = null;
    String mensaje = null;

    String listaID = form.getListaIds();
    if (log.isDebugEnabled())
        log.debug("los nombres de tareas que se quieren eliminar son " + listaID);

    String[] cadenaIds = listaID.split("#");
    trabajosIDs = new Long[cadenaIds.length];

    for (int i = 0; i < cadenaIds.length; i++) {
        trabajosIDs[i] = new Long(cadenaIds[i]);
    }

    ResourceBundle ficheroRecursos = null;

    try {

        Locale locale = request.getLocale();
        ficheroRecursos = this.getFicheroRecursos(locale);

        resultado = this.getSrvPlanificadorService().eliminarTrabajoEjecutado(trabajosIDs);

        if (resultado.booleanValue() == true) {
            mensaje = ficheroRecursos.getString("eliminarTareasPendientes.tareasEliminadasOk");
            resultadoString = ficheroRecursos.getString("tareas.OK");
        } else if (resultado.booleanValue() == false) {
            mensaje = ficheroRecursos.getString("eliminarTareasPendientes.tareasEliminadasError");
            resultadoString = ficheroRecursos.getString("tareas.ERROR");
        }

        form.setDescripcionBaja(mensaje);
        form.setResultado(resultadoString);

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

}

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

/**
 * Set up a custom property editor for converting form inputs to real
 * objects./*from   w  ww  . j a  va2s  .co  m*/
 * 
 * @param request
 *            the current request
 * @param binder
 *            the data binder
 */
@InitBinder
protected void initBinder(final HttpServletRequest request, final ServletRequestDataBinder binder) {
    binder.registerCustomEditor(Integer.class, null, new CustomNumberEditor(Integer.class, null, true));
    binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class, null, true));
    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    final SimpleDateFormat dateFormat = new SimpleDateFormat(this.getText("date.format", request.getLocale()));
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
}

From source file:fr.paris.lutece.plugins.calendar.modules.document.web.CalendarDocInsertServiceJspBean.java

/**
* Insert the specified url into HTML content
*
* @param request The HTTP request/*  w  w w . j av a  2 s.c  o m*/
* @return The url
*/
public String doInsertUrl(HttpServletRequest request) {
    init(request);

    String strDocumentId = request.getParameter(PARAMETER_DOCUMENT_ID);

    if ((strDocumentId == null) || !strDocumentId.matches(REGEX_ID)) {
        return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP);
    }

    String strInsert = request.getParameter(PARAMETER_DOCUMENT_ID);

    Map<String, String> model = new HashMap<String, String>();
    model.put(MARK_INPUT, _input);
    model.put(MARK_INSERT, strInsert);

    HtmlTemplate template;

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

    return template.getHtml();
}

From source file:org.guanxi.sp.engine.security.GuardVerifier.java

/**
 * Blocks Guard access to a service until the Guard can be verified.
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler//  w  w w.  ja v a2 s .  c  om
 * @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 guardID = request.getParameter(Guanxi.WAYF_PARAM_GUARD_ID);
    String sessionID = request.getParameter(Guanxi.WAYF_PARAM_SESSION_ID);

    if ((guardID == null) || (sessionID == null)) {
        logger.error("Cant' verify Guard due to missing parameter");
        request.setAttribute("error", messages.getMessage("engine.error.missing.guard.verification.parameter",
                null, request.getLocale()));
        request.setAttribute("message", messages.getMessage("engine.error.missing.guard.verification.parameter",
                null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    EntityDescriptorType guardEntityDescriptor = (EntityDescriptorType) servletContext.getAttribute(guardID);
    if (guardEntityDescriptor == null) {
        logger.error("Guard '" + guardID + "' not found in metadata repository");
        request.setAttribute("error",
                messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    Config config = (Config) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_CONFIG);
    if (config == null) {
        logger.error("Guard '" + guardID + "' wants to talk but Engine hasn't finished initialisation");
        request.setAttribute("error",
                messages.getMessage("engine.error.not.initialised", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.not.initialised", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Load the GuanxiGuardService node from the metadata
    GuardRoleDescriptorExtensions guardNativeMetadata = Util.getGuardNativeMetadata(guardEntityDescriptor);

    // Build the REST URL to verify the Guard's session
    String queryString = guardNativeMetadata.getVerifierURL() + "?" + Guanxi.SESSION_VERIFIER_PARAM_SESSION_ID
            + "=" + sessionID;

    // If we haven't already checked the Guard for secure comms, do it now
    if (servletContext.getAttribute(guardID + "SECURE_CHECK_DONE_SP") == null) {
        // Load up the Guard's native metadata...
        GuardRoleDescriptorExtensions guardExt = Util.getGuardNativeMetadata(guardEntityDescriptor);

        // ...and see if it's using HTTPS
        try {
            if (Util.isGuardSecure(guardExt)) {
                logger.info("Probing for Guard certificate for : " + guardID);

                /* If the Guard is using HTTPS then we'll need to connect to it, extract it's
                 * certificate and add it to our truststore. To do that, we'll need to use our
                 * own keystore to let the Guard authenticate us.
                 */
                EntityConnection guardConnection = new EntityConnection(queryString,
                        config.getCertificateAlias(), // alias of cert
                        config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(),
                        config.getTrustStorePassword(), EntityConnection.PROBING_ON);
                X509Certificate guardX509 = guardConnection.getServerCertificate();

                // We've got the Guard's X509 so add it to our truststore...
                KeyStore engineTrustStore = KeyStore.getInstance("jks");
                engineTrustStore.load(new FileInputStream(config.getTrustStore()),
                        config.getTrustStorePassword().toCharArray());
                // ...under it's Subject DN as an alias...
                engineTrustStore.setCertificateEntry(guardID, guardX509);
                // ...and rewrite the trust store
                engineTrustStore.store(new FileOutputStream(config.getTrustStore()),
                        config.getTrustStorePassword().toCharArray());

                // Mark Guard as having been checked for secure comms
                servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "SECURE");

                logger.info("Added : " + guardID + " to truststore");
            } else {
                // Mark Guard as having been checked for secure comms
                servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "NOT_SECURE");
            }
        } catch (Exception e) {
            logger.error("Failed to probe Guard : " + guardID + " for cert : ", e);
            request.setAttribute("error",
                    messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
            request.setAttribute("message",
                    messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
            request.getRequestDispatcher(errorPage).forward(request, response);
            return false;
        }
    }

    // Verify that the Guard actually sent the request
    String verificationResult = null;
    try {
        EntityConnection verifierService = new EntityConnection(queryString, config.getCertificateAlias(), // alias of cert
                config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(),
                config.getTrustStorePassword(), EntityConnection.PROBING_OFF);
        verifierService.setDoOutput(true);
        verifierService.connect();
        verificationResult = verifierService.getContentAsString();
    } catch (GuanxiException ge) {
        logger.error("Guard '" + guardID + "' error during verification : ", ge);
        request.setAttribute("error",
                messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Did the Guard verify the session?
    if (!verificationResult.equals(Guanxi.SESSION_VERIFIER_RETURN_VERIFIED)) {
        logger.error("Guard '" + guardID + "' error during verification : " + verificationResult);
        request.setAttribute("error",
                messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale()));
        request.setAttribute("message",
                messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    /* Convert the Guard's session ID to an Engine session ID and store the Guard's GuanxiGuardService
     * node under it.
     */
    servletContext.setAttribute(sessionID.replaceAll("GUARD", "ENGINE"), guardEntityDescriptor);

    return true;
}

From source file:fr.paris.lutece.plugins.asynchronousupload.service.AbstractAsynchronousUploadHandler.java

/**
 * {@inheritDoc}// w w w  . ja  v a  2s .c o m
 */
@Override
public void process(HttpServletRequest request, HttpServletResponse response, JSONObject mainObject,
        List<FileItem> listFileItemsToUpload) {
    mainObject.clear();

    String strFieldName = request.getParameter(PARAMETER_FIELD_NAME);

    if (StringUtils.isBlank(strFieldName)) {
        throw new AppException("id entry is not provided for the current file upload");
    }

    if ((listFileItemsToUpload != null) && !listFileItemsToUpload.isEmpty()) {
        String strError = canUploadFiles(request, strFieldName, listFileItemsToUpload, request.getLocale());

        if (strError == null) {
            for (FileItem fileItem : listFileItemsToUpload) {
                addFileItemToUploadedFilesList(fileItem, strFieldName, request);
            }
        } else {
            JSONUtils.buildJsonError(mainObject, strError);
        }
    }

    List<FileItem> fileItemsSession = getListUploadedFiles(strFieldName, request.getSession());

    JSONObject jsonListFileItems = JSONUtils.getUploadedFileJSON(fileItemsSession);
    mainObject.accumulateAll(jsonListFileItems);
    // add entry id to json
    mainObject.element(JSONUtils.JSON_KEY_FIELD_NAME, strFieldName);
}

From source file:fr.paris.lutece.plugins.helpdesk.web.HelpdeskApp.java

/**
 * Returns the contact form's result page
 * @param request The Http request//  w  w w .ja v a  2s . co  m
 * @return The Html template
 * @param faq The {@link Faq} concerned by contact form result
 * @throws SiteMessageException The Site message exception
 */
public String getContactFormResult(HttpServletRequest request, Faq faq) throws SiteMessageException {
    doSendQuestionMail(request);

    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_FAQ, faq);
    model.put(FULL_URL, request.getRequestURL());

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

    return template.getHtml();
}

From source file:org.jamwiki.servlets.UpgradeServlet.java

/**
 * This method handles the request after its parent class receives control.
 *
 * @param request - Standard HttpServletRequest object.
 * @param response - Standard HttpServletResponse object.
 * @return A <code>ModelAndView</code> object to be handled by the rest of the Spring framework.
 *//*from  ww  w  .  j  av a  2  s . c o m*/
public ModelAndView handleJAMWikiRequest(HttpServletRequest request, HttpServletResponse response,
        ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    if (!WikiUtil.isUpgrade()) {
        throw new WikiException(new WikiMessage("upgrade.error.notrequired"));
    }
    String function = request.getParameter("function");
    pageInfo.setPageTitle(new WikiMessage("upgrade.title",
            Environment.getValue(Environment.PROP_BASE_WIKI_VERSION), WikiVersion.CURRENT_WIKI_VERSION));
    boolean performUpgrade = (!StringUtils.isBlank(function) && function.equals("upgrade"));
    try {
        UpgradeUtil upgradeUtil = new UpgradeUtil(pageInfo.getMessages(), performUpgrade);
        upgradeUtil.upgrade(request.getLocale(), ServletUtil.getIpAddress(request));
    } catch (WikiException e) {
        pageInfo.addError(e.getWikiMessage());
    }
    if (performUpgrade) {
        upgrade(request, next, pageInfo);
    } else {
        next.addObject("viewOnly", "true");
        view(request, next, pageInfo);
    }
    return next;
}

From source file:org.squale.squaleweb.applicationlayer.action.results.application.ApplicationResultsAction.java

/**
 * Action exportPDF pour StyleReport ou iText
 * /*  w  w  w  .  j a v a2 s. co m*/
 * @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 exportPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException {
    Collection results = TableUtil.getSortedTable(request.getSession(), "resultListForm", "list");
    try {
        HashMap parameters = new HashMap();
        PDFDataJasperReports data = new PDFDataJasperReports(request.getLocale(), getResources(request),
                results, "/org/squale/squaleweb/resources/jasperreport/ApplicationResults.jasper", false,
                parameters);
        // Pour rcuprer les paramtres root
        parameters.put("applicationName", ((ResultListForm) form).getApplicationName());
        // La date ou le nom des audits
        parameters.put("auditDate", ((ResultListForm) form).getAuditName());
        parameters.put("previousAuditDate", ((ResultListForm) form).getPreviousAuditName());
        // L'image du pieChart
        parameters.put("pieChart", (java.awt.Image) request.getSession().getAttribute("pieChart"));
        // Rcupration des donnes sur la volumtrie des projets de l'application
        // Prparation de l'appel  la couche mtier
        IApplicationComponent ac = AccessDelegateHelper.getInstance("Graph");
        Long pCurrentAuditId = new Long(Long.parseLong(((ResultListForm) form).getCurrentAuditId()));
        Object[] paramAuditId = { pCurrentAuditId };
        // Recherche des donnes PieChart
        JFreeChart pieChart;
        Object[] maps = (Object[]) ac.execute("getApplicationPieChartGraph", paramAuditId);
        // On rcupre la volumtrie par grille
        final int indexVol = 2;
        PieChartMaker pieMaker = new PieChartMaker(null, null, null);
        pieMaker.setValues((Map) maps[indexVol]);
        pieChart = pieMaker.getChart(new HashMap(), request);
        // L'image du pieChart pour la volumetrie par grille
        parameters.put("gridPieChart",
                pieChart.createBufferedImage(PieChartMaker.DEFAULT_WIDTH, PieChartMaker.DEFAULT_HEIGHT));
        // L'image du kiviat
        parameters.put("kiviatChart", (java.awt.Image) request.getSession().getAttribute("kiviatChart")); // Le
        // nom
        // de
        // l'utilisateur
        LogonBean logon = (LogonBean) request.getSession().getAttribute(WConstants.USER_KEY);
        parameters.put("userName", logon.getMatricule());
        PDFFactory.generatePDFToHTTPResponse(data, response, "", PDFEngine.JASPERREPORTS);
    } catch (Exception e) {
        throw new ServletException(e);
    }
    return null;
}