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.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Handles input from the web form to generate and sign a CSR and store the resulting
 * certificate chain in a keystore.//from   w  w w .j  a  va2 s . com
 *
 * @param request Standard issue HttpServletRequest
 * @param response Standard issue HttpServletResponse
 * @throws ServletException
 */
@SuppressWarnings("unchecked")
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException {

    RegisterGuard form = (RegisterGuard) command;
    String escapedGuardID = FileName.encode(form.getGuardid().toLowerCase());

    // Adjust the metadata directory for the new Guard
    String metadataDirectory = config.getGuardsMetadataDirectory() + File.separator + escapedGuardID;

    // Create the new Guard metadata directory
    if (!createGuardMetadataDirectory(metadataDirectory)) {
        ModelAndView mAndV = new ModelAndView();
        mAndV.setViewName(errorView);
        mAndV.getModel().put(errorViewDisplayVar,
                messageSource.getMessage("register.guard.error.create.dir", null, request.getLocale()));
        return mAndV;
    }

    // Build an X509 name
    String x509DN = "CN=" + RFC2253.encode(form.getGuardid());
    x509DN += ",OU=" + RFC2253.encode(form.getOrgunit());
    x509DN += ",O=" + RFC2253.encode(form.getOrg());
    x509DN += ",L=" + RFC2253.encode(form.getCity());
    x509DN += ",ST=" + RFC2253.encode(form.getLocality());
    x509DN += ",C=" + RFC2253.encode(form.getCountry());

    // Generate a CSR and sign it
    CABean caBean = createSignedCertificateChain(x509DN, config.getKeyType());

    // Use a random number for the keystore password
    Random randomNumberGenerator = new Random();
    String keystorePassword = String.valueOf(randomNumberGenerator.nextInt());

    /* Store the certificate chain in a keystore. The name of the keystore must
     * correspond to the ID of the Guard that will use it. i.e. when the Engine
     * masquerades for the Guard over the SSL connection to the IdP, it must
     * know where the Guard's keystore is.
     * To this end the keystore will be the lowercase equivalent of the Guard ID
     * and it's certificate alias will be the same.
     */
    String guardKeystore = metadataDirectory + File.separator + escapedGuardID + ".jks";
    createKeystoreWithChain(guardKeystore, form.getGuardid().toLowerCase(), keystorePassword, caBean);

    createGuardMetadataFile(metadataDirectory, guardKeystore, keystorePassword, form, caBean);

    // Load the new Guard so the main Engine can use it
    loadGuardMetadata(metadataDirectory + File.separator + escapedGuardID + ".xml");

    // Show the certificate chain to the user
    displayChain(request, response, caBean);

    return new ModelAndView(getSuccessView(), errors.getModel());
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

/**
 * @param userName//from  w  w  w.  j a  v a 2 s  . co  m
 * @param pickValFromReset
 * @param request
 * @return
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
@RequestMapping(value = "/request_call_by_user", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> requestCall(
        @RequestParam(value = "userName", required = false) final String userName,
        @RequestParam(value = "pickValFromReset", required = false) final String pickValFromReset,
        HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {
    Map<String, String> returnResponse = new HashMap<String, String>();
    String generatedPhoneVerificationPin = request.getSession().getAttribute("phoneVerificationPin").toString();
    final String userNameLoc;

    if (pickValFromReset != null && pickValFromReset.equals("pick")) {
        userNameLoc = (String) request.getSession().getAttribute(RESET_USER_KEY);
    } else if (userName != null) {
        userNameLoc = userName;
    } else {
        returnResponse.put("result", "failed");
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.callFailed", null, request.getLocale()));
        return returnResponse;
    }

    request.getSession().setAttribute("userName", userNameLoc);
    User user = null;
    try {
        user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

            @Override
            public User run() {
                User user = userService.getUserByParam("username", userNameLoc, false);
                return user;
            }
        });
    } catch (NoSuchUserException e) {
    }

    if (user == null) {
        returnResponse.put("result", "failed");
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.callFailed", null, request.getLocale()));
        return returnResponse;
    }

    try {
        String refId = ((TelephoneVerificationService) connectorManagementService
                .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).requestCall(
                        user.getCountryCode(), user.getPhoneWithoutIsdCode(), generatedPhoneVerificationPin);
        if (refId != null) {
            returnResponse.put("result", "success");
            returnResponse.put("message",
                    messageSource.getMessage("js.errors.register.callRequested", null, request.getLocale()));
        } else {
            returnResponse.put("result", "failed");
            returnResponse.put("message",
                    messageSource.getMessage("js.errors.register.callFailed", null, request.getLocale()));
        }
    } catch (TelephoneVerificationServiceException e) {
        returnResponse.put("result", "failed");
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.callFailed", null, request.getLocale()));
    }

    return returnResponse;
}

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

/**
 * Redirige vers une jsp affichant le scatterplott
 * /*from  w ww.jav a  2  s.  c o  m*/
 * @param pMapping le mapping.
 * @param pForm le formulaire  lire.
 * @param pRequest la requte HTTP.
 * @param pResponse la rponse de la servlet.
 * @return l'action  raliser.
 */
public ActionForward displayComponents(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest,
        HttpServletResponse pResponse) {
    ActionForward forward = null;
    ActionErrors errors = new ActionErrors();
    try {
        // if request is not build correctly
        forward = pMapping.findForward("total_failure");
        // retrieve tres and values in request
        String tres = pRequest.getParameter(TRE_KEYS_KEYWORD);
        String values = pRequest.getParameter(TRE_VALUES_KEYWORD);
        if (null != tres && tres.length() > 0 && null != values && values.length() > 0) {
            String[] treKeys = tres.split(",");
            String[] treValues = values.split(",");
            IApplicationComponent ac = AccessDelegateHelper.getInstance("Results");
            Object[] paramIn = { new Long(((RootForm) pForm).getProjectId()),
                    new Long(((RootForm) pForm).getCurrentAuditId()), treKeys, treValues,
                    new Integer(WebMessages.getString(pRequest.getLocale(), "component.max")) };
            // Number of components is limited
            List result = (List) ac.execute("getComponentsWhereTres", paramIn);
            WTransformerFactory.objToForm(ComponentResultListTransformer.class, (WActionForm) pForm,
                    new Object[] { result, treKeys, treValues });
            forward = pMapping.findForward("success");
        }
    } catch (NumberFormatException nfe) {
        // error in request
        handleException(nfe, errors, pRequest);
    } catch (JrafEnterpriseException jee) {
        handleException(jee, errors, pRequest);
    } catch (WTransformerException wte) {
        handleException(wte, errors, pRequest);
    }
    if (!errors.isEmpty()) {
        saveMessages(pRequest, errors);
        forward = pMapping.findForward("total_failure");
    }
    return forward;
}

From source file:fr.paris.lutece.plugins.workflow.modules.ticketing.service.task.TaskEditTicket.java

/**
 * Process the task for user side/* ww  w .j av a  2 s .  c o m*/
 * @param nIdResourceHistory the ResourceHistory id
 * @param request the request
 * @param locale the locale
 * @param config the task configuration
 * @return the information message to store
 */
private String processUserTask(int nIdResourceHistory, HttpServletRequest request, Locale locale,
        TaskEditTicketConfig config) {
    String strTaskInformation = StringUtils.EMPTY;
    StringBuilder sbEntries = new StringBuilder();

    String strUserMessage = request.getParameter(PARAMETER_USER_MESSAGE);

    // We get the ticket to modify
    Ticket ticket = getTicket(nIdResourceHistory);

    EditableTicket editableTicket = _editableTicketService.findByIdTicket(ticket.getId());

    List<Entry> listEntriesToEdit = _editableTicketService.buildListEntriesToEdit(request,
            editableTicket.getListEditableTicketFields());

    for (Entry entry : listEntriesToEdit) {
        Iterator<Response> iterator = ticket.getListResponse().iterator();

        while (iterator.hasNext()) {
            Response response = iterator.next();

            if (response.getEntry().getIdEntry() == entry.getIdEntry()) {
                iterator.remove();
            }
        }

        _ticketFormService.getResponseEntry(request, entry.getIdEntry(), request.getLocale(), ticket);
        sbEntries.append(entry.getTitle()).append(SEPARATOR);
    }

    // remove and add generic attributes responses
    TicketHome.removeTicketResponse(ticket.getId());

    if ((ticket.getListResponse() != null) && !ticket.getListResponse().isEmpty()) {
        for (Response response : ticket.getListResponse()) {
            ResponseHome.create(response);
            TicketHome.insertTicketResponse(ticket.getId(), response.getIdResponse());
        }
    }

    if (sbEntries.length() != 0) {
        sbEntries.delete(sbEntries.length() - SEPARATOR.length(), sbEntries.length());
    }

    ticket.setUserMessage(strUserMessage);
    TicketHome.update(ticket);

    editableTicket.setIsEdited(true);
    _editableTicketService.update(editableTicket);

    if (StringUtils.isEmpty(strUserMessage)) {
        strUserMessage = I18nService.getLocalizedString(MESSAGE_EDIT_TICKET_INFORMATION_NO_MESSAGE,
                Locale.FRENCH);
    }

    if (sbEntries.length() == 0) {
        strTaskInformation = MessageFormat.format(I18nService.getLocalizedString(
                MESSAGE_EDIT_TICKET_INFORMATION_VIEW_USER_NO_FIELD_EDITED, Locale.FRENCH), strUserMessage);
    } else {
        strTaskInformation = MessageFormat.format(
                I18nService.getLocalizedString(MESSAGE_EDIT_TICKET_INFORMATION_VIEW_USER, Locale.FRENCH),
                sbEntries.toString(), strUserMessage);
    }

    return strTaskInformation;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

/**
 * @param userName/*from   ww w.j  a va2 s. c  o  m*/
 * @param pickValFromReset
 * @param request
 * @return
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
@RequestMapping(value = "/request_sms_by_user", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> requestSMS(@RequestParam(value = "userName", required = false) final String userName,
        @RequestParam(value = "pickValFromReset", required = false) final String pickValFromReset,
        HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {
    String generatedPhoneVerificationPin = request.getSession().getAttribute("phoneVerificationPin").toString();
    final String userNameLoc;
    Map<String, String> returnResponse = new HashMap<String, String>();

    if (pickValFromReset != null && pickValFromReset.equals("pick")) {
        userNameLoc = (String) request.getSession().getAttribute(RESET_USER_KEY);
    } else if (userName != null) {
        userNameLoc = userName;
    } else {
        returnResponse.put("result", "failed");
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.textMessageFailed", null, request.getLocale()));
        return returnResponse;
    }

    request.getSession().setAttribute("userName", userNameLoc);
    User user = null;
    try {
        user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

            @Override
            public User run() {
                User user = userService.getUserByParam("username", userNameLoc, false);
                return user;
            }
        });
    } catch (NoSuchUserException e) {
    }

    if (user == null) {
        returnResponse.put("result", "success"); // Returning success for security
        // reason.
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.textMessageRequested", null, request.getLocale()));
        return returnResponse;
    }

    try {
        String refId = ((TelephoneVerificationService) connectorManagementService
                .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).requestSMS(
                        user.getCountryCode(), user.getPhoneWithoutIsdCode(), generatedPhoneVerificationPin);
        if (refId != null) {
            returnResponse.put("result", "success");
            returnResponse.put("message", messageSource.getMessage("js.errors.register.textMessageRequested",
                    null, request.getLocale()));
        } else {
            returnResponse.put("result", "failed");
            returnResponse.put("message", messageSource.getMessage("js.errors.register.textMessageFailed", null,
                    request.getLocale()));
        }
    } catch (TelephoneVerificationServiceException e) {
        returnResponse.put("result", "failed");
        returnResponse.put("message",
                messageSource.getMessage("js.errors.register.textMessageFailed", null, request.getLocale()));
    }

    return returnResponse;
}

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

/**
 * Send comment notification.//from  w  ww. jav a 2 s.  co m
 * 
 * @param request the request
 * @param comment the document comment
 * @param config the config
 */
private void sendCommentNotification(HttpServletRequest request, Comment comment,
        CommentExtenderConfig config) {
    int nMailingListId = config.getIdMailingList();
    Collection<Recipient> listRecipients = AdminMailingListService.getRecipients(nMailingListId);

    for (Recipient recipient : listRecipients) {
        Map<String, Object> model = new HashMap<String, Object>();

        String strSenderEmail = comment.getEmail();
        String strSenderName = comment.getName();
        String strResourceName = getResourceExtenderService().getExtendableResourceName(
                comment.getIdExtendableResource(), comment.getExtendableResourceType());

        Object[] params = { strResourceName };
        String strSubject = I18nService.getLocalizedString(CommentConstants.MESSAGE_NOTIFY_SUBJECT, params,
                request.getLocale());

        UrlItem url = new UrlItem(AppPathService.getBaseUrl(request) + AppPathService.getPortalUrl());
        url.addParameter(XPageAppService.PARAM_XPAGE_APP, CommentPlugin.PLUGIN_NAME);
        url.addParameter(CommentConstants.PARAMETER_ID_EXTENDABLE_RESOURCE, comment.getIdExtendableResource());
        url.addParameter(CommentConstants.PARAMETER_EXTENDABLE_RESOURCE_TYPE,
                comment.getExtendableResourceType());

        model.put(CommentConstants.MARK_RESOURCE_EXTENDER_NAME, strResourceName);
        model.put(CommentConstants.MARK_RESOURCE_EXTENDER_URL, url.getUrl());
        model.put(CommentConstants.MARK_COMMENT, comment);

        HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_COMMENT_NOTIFY_MESSAGE,
                request.getLocale(), model);
        String strBody = template.getHtml();

        MailService.sendMailHtml(recipient.getEmail(), strSenderName, strSenderEmail, strSubject, strBody);
    }
}

From source file:com.jaspersoft.jasperserver.war.themes.ThemeResolverServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Check if we can find a resource in the current theme
    //String resPath = req.getRequestURI().substring((req.getContextPath() + req.getServletPath()).length());
    String resPath = req.getRequestURI().substring(req.getContextPath().length() + 1);
    ThemeResource themeResource = themeCache.getThemeResource(resPath);
    if (themeResource == null) {
        resp.sendError(404);//  w w  w.  j  av a  2  s  .  c om
        return;
    }

    // Set contentType
    String filename = resPath;
    if (filename.indexOf("/") >= 0) {
        filename = filename.substring(filename.lastIndexOf("/") + 1);
    }
    String contentType = servletContext.getMimeType(filename);
    if (contentType == null) {
        log.error("Cannot detect a response content type for the file : " + filename);
        resp.sendError(404);
        return;
    }
    resp.setContentType(contentType);

    // Get Last Modified date
    Date lastModified = themeResource.getLastModified();
    // Get rid of ms
    lastModified.setTime(lastModified.getTime() / 1000 * 1000);

    // Set cache controlling HTTP Response Headers
    DateFormat df = getFormat(req.getLocale());
    resp.setHeader("Cache-Control", "max-age=" + expiresInSecs + ", public");
    resp.setHeader("Pragma", "");
    resp.setHeader("Last-Modified", df.format(lastModified));
    resp.setHeader("Expires", df.format(new Date(new Date().getTime() + expiresInSecs * 1000)));

    // Send 304 if resource has not been modified since last time requested
    String ifModSince = req.getHeader("If-Modified-Since");
    try {
        Date modDate = df.parse(ifModSince);
        if (!lastModified.after(modDate)) {
            resp.setStatus(304);
            return;
        }
    } catch (Exception e) {
    }

    // Send the full content
    resp.setContentLength(themeResource.getContent().length);
    ServletOutputStream os = resp.getOutputStream();
    os.write(themeResource.getContent());
    os.flush();
    os.close();
}

From source file:fr.paris.lutece.plugins.mylutece.modules.database.authentication.web.MyLuteceDatabaseApp.java

/**
 * //from   www  .j a v a 2s  .  co  m
 * @param request The HTTP request
 * @param plugin The plugin
 */
public void init(HttpServletRequest request, Plugin plugin) {
    _locale = request.getLocale();
    _plugin = plugin;
}

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

/**
 * Send a notification to all the admins when all the tickets of an
 * offer are booked/*from www. j a va2 s. c om*/
 * @param request The HTTP request
 * @param purchase
 */
private void sendNotificationToAdmins(HttpServletRequest request, ReservationDTO purchase) {
    SeanceDTO seance = this._serviceOffer.findSeanceById(purchase.getOffer().getId());

    if (seance != null && seance.getQuantity() < seance.getMinTickets()) {
        //Generate mail content
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(MARK_SEANCE, seance);
        model.put(MARK_BASE_URL, AppPathService.getBaseUrl(request));

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

        Collection<AdminUser> listUsers = (List<AdminUser>) AdminUserHome.findUserList();

        for (AdminUser adminUser : listUsers) {
            // Create mail object
            NotificationDTO notificationDTO = new NotificationDTO();
            notificationDTO.setRecipientsTo(adminUser.getEmail());

            String[] args = new String[] { String.valueOf(seance.getId()) };
            notificationDTO.setSubject(I18nService.getLocalizedString(
                    MESSAGE_NOTIFICATION_ADMIN_OFFER_QUANTITY_SUBJECT, args, request.getLocale()));
            notificationDTO.setMessage(template.getHtml());

            // Send it
            _serviceNotification.send(notificationDTO);
        }
    }
}

From source file:fr.paris.lutece.plugins.workflow.modules.notifygru.web.NotifyGruTaskComponent.java

/**
 * {@inheritDoc}//from   www  .j  av  a 2  s  .c o  m
 *
 * @param request
 * @param locale
 * @param task
 * @return
 */
@Override
public String getDisplayConfigForm(HttpServletRequest request, Locale locale, ITask task) {
    TaskNotifyGruConfig config = _taskNotifyGruConfigService.findByPrimaryKey(task.getId());
    if (config == null) {
        //no config stored yet for this task, setting a empty one
        config = new TaskNotifyGruConfig();
    }

    String strDefaultSenderName = AppPropertiesService
            .getProperty(Constants.PROPERTY_NOTIFY_MAIL_DEFAULT_SENDER_NAME);

    Map<String, Object> model = new HashMap<String, Object>();

    model.put(Constants.MARK_CONFIG, config);
    model.put(Constants.MARK_DEFAULT_SENDER_NAME, strDefaultSenderName);

    if (config.getIdSpringProvider() == null) {
        model.put(Constants.MARK_SELECT_PROVIDER, ServiceConfigTaskForm.getListProvider(task));
    }

    ReferenceList listeOnglet = ServiceConfigTaskForm.getListOnglet(config, locale);

    if (listeOnglet.size() > 0) {
        model.put(Constants.MARK_LIST_ONGLET, listeOnglet);
    }

    model.put(Constants.MARK_MAILING_LIST, _notifyGRUService.getMailingList(request));

    model.put(Constants.MARK_LOCALE, request.getLocale());
    model.put(Constants.MARK_WEBAPP_URL, AppPathService.getBaseUrl(request));

    if ((config.getIdSpringProvider() != null)) {
        //_providerService = SpringContextService.getBean( config.getIdSpringProvider(  ) );
        _providerService = ServiceConfigTaskForm.getCostumizeBean(config.getIdSpringProvider(), task);

        String strTemplateProvider = (_providerService == null) ? "" : _providerService.getInfosHelp(locale);

        model.put(Constants.MARK_HELPER_PROVIDER, strTemplateProvider);
    }

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_TASK_NOTIFY_GRU_CONFIG, locale, model);

    return template.getHtml();
}