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:fr.paris.lutece.plugins.workflow.modules.rest.rs.WorkflowRest.java

/**
 * Get the wadl.xml content//w w  w  .  j  a v  a 2  s.  c  om
 * @param request {@link HttpServletRequest}
 * @return the content of wadl.xml
 */
@GET
@Path(WorkflowRestConstants.PATH_WADL)
@Produces(MediaType.APPLICATION_XML)
public String getWADL(@Context HttpServletRequest request) {
    StringBuilder sbBase = new StringBuilder(AppPathService.getBaseUrl(request));

    if (sbBase.toString().endsWith(WorkflowRestConstants.SLASH)) {
        sbBase.deleteCharAt(sbBase.length() - 1);
    }

    sbBase.append(RestConstants.BASE_PATH + WorkflowPlugin.PLUGIN_NAME);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(WorkflowRestConstants.MARK_BASE_URL, sbBase.toString());

    HtmlTemplate t = AppTemplateService.getTemplate(WorkflowRestConstants.TEMPLATE_WADL, request.getLocale(),
            model);

    return t.getHtml();
}

From source file:org.dspace.app.webui.cris.controller.FormSendMailController.java

protected Object formBackingObject(HttpServletRequest request) throws Exception {

    String mode_s = request.getParameter("mode");
    Integer mode = Integer.parseInt(mode_s);
    String id_s = request.getParameter("id");
    Integer id = null;/*from   w w  w .j  a v  a  2  s .c om*/
    if (id_s != null) {
        id = Integer.parseInt(id_s);
    }
    ResearcherPage researcher = applicationService.get(ResearcherPage.class, id);
    MailDTO dto = new MailDTO();
    dto.setSubmitter(researcher.getId());
    dto.setRp(ResearcherPageUtils.getPersistentIdentifier(researcher));
    Locale supportedLocale = request.getLocale();
    ResourceBundle labels = ResourceBundle.getBundle("Messages", supportedLocale);
    switch (mode) {

    case MODE_BIBLIOMETRIC:
        dto.setTemplate(TEMPLATE_BIBLIOMETRIC);
        dto.setSubject(labels.getString("subject.mail.hku.request-changes.two"));
        break;

    case MODE_ITEMS:
        dto.setTemplate(TEMPLATE_ITEMS);
        dto.setSubject(labels.getString("subject.mail.hku.request-changes.three"));
        break;

    default:
        dto.setTemplate(TEMPLATE_MEDIA);
        dto.setSubject(labels.getString("subject.mail.hku.request-changes.one"));
        break;
    }
    return dto;
}

From source file:com.ningpai.common.util.CaptchaController.java

@RequestMapping("/captcha")
public void writeCaptcha(HttpServletRequest request, HttpServletResponse response) {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {//from   ww  w  . j a v a 2s  . c  om
        // get the session id that will identify the generated captcha.
        // the same id must be used to validate the response, the session id is a good candidate!
        String captchaId = request.getSession().getId();
        BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());
        try {
            ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
        } catch (IOException e) {
        }
    } catch (IllegalArgumentException e) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e1) {
        }
        return;
    } catch (CaptchaServiceException e) {
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e1) {
        }
        return;
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // flush it in the response
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);

    ServletOutputStream responseOutputStream;
    try {
        responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    } catch (IOException e) {
    }

}

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

/**
 * On submit./*from  ww  w .  j a v  a 2  s  .c  o m*/
 * 
 * @param fileUpload
 *            the file upload
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final FileUpload fileUpload, final BindingResult errors,
        final HttpServletRequest request) throws Exception {

    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.validator != null) { // validator is null during testing
        this.validator.validate(fileUpload, errors);

        if (errors.hasErrors())
            return "fileupload";
    }

    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
        final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");

        return "fileupload";
    }

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

    // the directory to upload to
    final String uploadDir = this.getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser()
            + "/";

    // Create the directory if it doesn't exist
    final File dirPath = new File(uploadDir);

    if (!dirPath.exists()) {
        dirPath.mkdirs();
    }

    // retrieve the file data
    final InputStream stream = file.getInputStream();

    // write the file to the file specified
    final OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
    int bytesRead;
    final byte[] buffer = new byte[8192];

    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, bytesRead);
    }

    bos.close();

    // close the stream
    stream.close();

    // place the data into the request for retrieval on next page
    request.setAttribute("friendlyName", fileUpload.getName());
    request.setAttribute("fileName", file.getOriginalFilename());
    request.setAttribute("contentType", file.getContentType());
    request.setAttribute("size", file.getSize() + " bytes");
    request.setAttribute("location",
            dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename());

    final String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/";
    request.setAttribute("link", link + file.getOriginalFilename());

    return this.getSuccessView();
}

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

/**
 *
 *//*from   ww  w. j a  v a2 s.  c om*/
private void importFile(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) {
    try {
        List<FileItem> fileItems = ServletUtil.processMultipartRequest(request);
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {
                continue;
            }
            File file = saveFileItem(fileItem);
            WikiUser user = ServletUtil.currentWikiUser();
            String virtualWiki = pageInfo.getVirtualWikiName();
            String ipAddress = ServletUtil.getIpAddress(request);
            Locale locale = request.getLocale();
            List<String> successfulImports = MigrationUtil.importFromFile(file, virtualWiki, user, ipAddress,
                    locale);
            file.delete();
            next.addObject("successfulImports", successfulImports);
            break;
        }
    } catch (MigrationException e) {
        logger.error("Failure while importing from file", e);
        pageInfo.addError(new WikiMessage("import.error.migration", e.getMessage()));
    } catch (WikiException e) {
        logger.error("Failure while importing from file", e);
        pageInfo.addError(e.getWikiMessage());
    }
    view(request, next, pageInfo);
}

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

/**
 * Delete case.// w  ww .  j a v a2  s  .  c  o  m
 * 
 * @param alphaCase
 *            the alpha case
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST, params = { "deleteCase" })
public String deleteCase(final AlphaCase alphaCase, final BindingResult errors,
        final HttpServletRequest request) throws Exception {
    this.caseManager.remove(alphaCase.getCaseId());
    this.saveMessage(request, this.getText("case.deleted", request.getLocale()));
    return this.getCancelView();
}

From source file:org.zht.framework.filter.jcaptcha.JCaptchaFilter.java

/**
 * ???./*from   ww w  . j  a va2s .  com*/
 */
protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    response.setDateHeader("Expires", 0);
    response.addHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setContentType("image/jpeg");

    ServletOutputStream out = response.getOutputStream();
    try {
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId,
                request.getLocale());
        ImageIO.write(challenge, "jpg", out);
        out.flush();
    } catch (CaptchaServiceException e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
    }
}

From source file:fr.paris.lutece.plugins.workflow.modules.ticketing.web.EditTicketXPage.java

/**
 * Get the page to edit the ticket//  w  ww. jav  a 2  s. com
 * @param request the HTTP request
 * @param editableTicket the editable ticket
 * @return a XPage
 * @throws SiteMessageException a site message if there is a problem
 */
private XPage getEditTicketPage(HttpServletRequest request, EditableTicket editableTicket)
        throws SiteMessageException {
    XPage page = new XPage();

    List<Entry> listEntries = _editableTicketService.buildListEntriesToEdit(request,
            editableTicket.getListEditableTicketFields());
    Ticket ticket = WorkflowTicketingUtils.findTicketByIdHistory(editableTicket.getIdHistory());

    String htmlForm = _ticketFormService.getHtmlForm(listEntries, request.getLocale(), true, request);
    TicketAsynchronousUploadHandler.getHandler().removeSessionFiles(request.getSession().getId());

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(TaskEditTicketConstants.MARK_EDITABLE_TICKET, editableTicket);
    model.put(TicketingConstants.MARK_TICKET, ticket);
    model.put(MARK_ID_ACTION, request.getParameter(TaskEditTicketConstants.PARAMETER_ID_ACTION));
    model.put(TaskEditTicketConstants.MARK_ENTRIES_HTML_FORM, htmlForm);
    model.put(MARK_SIGNATURE, request.getParameter(TaskEditTicketConstants.PARAMETER_SIGNATURE));
    model.put(MARK_TIMESTAMP, request.getParameter(TaskEditTicketConstants.PARAMETER_TIMESTAMP));

    TicketHelper.storeReadOnlyHtmlResponsesIntoModel(request, model, ticket);

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

    page.setTitle(I18nService.getLocalizedString(PROPERTY_XPAGE_EDIT_TICKET_PAGETITLE, request.getLocale()));
    page.setPathLabel(
            I18nService.getLocalizedString(PROPERTY_XPAGE_EDIT_TICKET_PATHLABEL, request.getLocale()));
    page.setContent(template.getHtml());

    return page;
}

From source file:com.octo.captcha.module.struts.image.RenderImageCaptchaAction.java

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    ImageCaptchaService service = (ImageCaptchaService) CaptchaServicePlugin.getInstance().getService();
    String captchaID = CaptchaModuleConfigHelper.getId(httpServletRequest);
    //(String) theRequest.getParameter(captchaIDParameterName);

    // call the ManageableImageCaptchaService methods
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/*  w w  w .  ja  v  a  2  s.c  o  m*/
        BufferedImage challenge = service.getImageChallengeForID(captchaID, httpServletRequest.getLocale());
        // the output stream to render the captcha image as jpeg into

        // a jpeg encoder
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
        jpegEncoder.encode(challenge);
    } catch (IllegalArgumentException e) {
        // log a security warning and return a 404...
        if (log.isWarnEnabled()) {
            log.warn("There was a try from " + httpServletRequest.getRemoteAddr()
                    + " to render an URL without ID" + " or with a too long one");
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            log.error("should never pass here!");
            return actionMapping.findForward("error");
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        log.warn("Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        // log.error("should never pass here!");
        return actionMapping.findForward("error");
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
    // log.error("should never pass here!");
    return null;
}

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

/**
 * handles the case, if the user clicks on one of the buttons.
 * //  ww  w.  j  a  va 2s  . c  o  m
 * @param newAdornment
 *            the new adornment
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @return success
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final Adornment newAdornment, final BindingResult errors,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    final String adornmentId = request.getParameter("adornmentId");
    final String cardId = request.getParameter("card");
    final String caseId = request.getParameter("case");
    final String success = this.getSuccessView();
    final Locale locale = request.getLocale();
    this.setupAdornmentTypes(caseId, cardId);

    final AlphaCardIdentifier alphaCardIdentifier = new AlphaCardIdentifier(caseId, cardId);
    AlphaCard card = this.alphaCardManager.get(alphaCardIdentifier);

    if (request.getParameter("delete") != null) {
        if (AdornmentType.fromName(newAdornment.getName()) == null) {
            card.getAlphaCardDescriptor().deleteAdornment(newAdornment.getName());
            this.saveMessage(request, this.getText("adornment.deleted", locale));
        } else {
            newAdornment.setValue("");
            if (AdornmentRules.applyRules(card, newAdornment)) {
                card.getAlphaCardDescriptor().setAdornment(newAdornment);
                this.saveMessage(request, this.getText("adornment.deleted", locale));
            } else {
                this.saveError(request, this.getText("adornment.errorDelete", locale));
                return this.getCancelView();
            }
        }

    } else {
        if (newAdornment.getName() == AdornmentType.DataProvision.getName()) {
            this.saveError(request, this.getText("adornment.errorChange", locale));
            return this.getCancelView();
        }
        if (AdornmentRules.applyRules(card, newAdornment)) {
            final boolean isNew = card.getAlphaCardDescriptor().getAdornment(newAdornment.getName()) == null;
            card.getAlphaCardDescriptor().setAdornment(newAdornment);
            final String key = (isNew) ? "adornment.added" : "adornment.updated";
            this.saveMessage(request, this.getText(key, locale));
        } else {
            this.saveError(request, this.getText("adornment.errorChange", locale));
            return this.getCancelView();
        }
    }

    // update Data Provision Adornment after any adornment change
    card.getAlphaCardDescriptor().setAdornment(AdornmentType.DataProvision.getName(),
            AdornmentRules.getDataProvisionStatus(card));

    if (card.getAlphaCardDescriptor().isAdornmentsChanged()) {
        card = this.alphaCardManager.save(card);
    }

    return success;
}