Example usage for javax.servlet.http HttpServletRequest getLocales

List of usage examples for javax.servlet.http HttpServletRequest getLocales

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getLocales.

Prototype

public Enumeration<Locale> getLocales();

Source Link

Document

Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header.

Usage

From source file:org.apache.catalina.authenticator.FormAuthenticator.java

/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 *//*from   w w  w. jav a2 s. co m*/
private void saveRequest(HttpRequest request, Session session) {

    // Create and populate a SavedRequest object for this request
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++)
            saved.addCookie(cookies[i]);
    }
    Enumeration names = hreq.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = hreq.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration locales = hreq.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        saved.addLocale(locale);
    }
    Map parameters = hreq.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();
    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        String paramValues[] = (String[]) parameters.get(paramName);
        saved.addParameter(paramName, paramValues);
    }
    saved.setMethod(hreq.getMethod());
    saved.setQueryString(hreq.getQueryString());
    saved.setRequestURI(hreq.getRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(Constants.FORM_REQUEST_NOTE, saved);

}

From source file:org.auraframework.http.AuraContextFilter.java

protected AuraContext startContext(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;

    Format f = format.get(request);
    Authentication a = access.get(request, Authentication.AUTHENTICATED);

    Map<String, Object> configMap = getConfigMap(request);
    Mode m = getMode(request, configMap);
    boolean d = getDebugToolParam(request);

    DefDescriptor<? extends BaseComponentDef> appDesc = getAppParam(request, configMap);

    if (componentDir != null) {
        System.setProperty("aura.componentDir", componentDir);
    }/* w ww  .  j  a  v  a  2 s  .  c  om*/
    //
    // FIXME: our usage of format should be revisited. Most URLs have
    // a fixed format, so we should have a way of getting that.
    //
    if (f == null) {
        if ("GET".equals(request.getMethod())) {
            f = Format.HTML;
        } else {
            f = Format.JSON;
        }
    }
    AuraContext context = Aura.getContextService().startContext(m, f, a, appDesc, d);

    String contextPath = request.getContextPath();
    // some appservers (like tomcat) use "/" as the root path, others ""
    if ("/".equals(contextPath)) {
        contextPath = "";
    }
    context.setContextPath(contextPath);
    context.setNum(num.get(request));
    context.setRequestedLocales(Collections.list(request.getLocales()));
    context.setClient(new Client(request.getHeader(HttpHeaders.USER_AGENT)));
    if (configMap != null) {
        getLoaded(context, configMap.get("loaded"));
        @SuppressWarnings("unchecked")
        List<Object> dns = (List<Object>) configMap.get("dn");
        if (dns != null) {
            for (Object dn : dns) {
                context.addDynamicNamespace((String) dn);
            }
        }
        context.setFrameworkUID((String) configMap.get("fwuid"));

        @SuppressWarnings("unchecked")
        List<String> themes = (List<String>) configMap.get("themes");
        if (themes != null) {
            try {
                DefinitionService ds = Aura.getDefinitionService();
                for (String theme : themes) {
                    context.appendThemeDescriptor(ds.getDefDescriptor(theme, ThemeDef.class));
                }
            } catch (QuickFixException e) {
                throw new AuraRuntimeException(e);
            }
        }
    }

    if (!isProduction) {
        TestContextAdapter testContextAdapter = Aura.get(TestContextAdapter.class);
        if (testContextAdapter != null) {
            String testName = null;
            // config takes precedence over param because the value is not expected to change during a test and it
            // is less likely to have been modified unintentionally when from the config
            if (configMap != null) {
                testName = (String) configMap.get("test");
            }
            if (testName == null) {
                testName = test.get(request);
            }
            if (testName != null) {
                TestContext testContext = testContextAdapter.getTestContext(testName);
                if (testContext != null) {
                    MasterDefRegistry registry = context.getDefRegistry();
                    Set<Definition> mocks = testContext.getLocalDefs();
                    if (mocks != null) {
                        boolean doReset = testReset.get(request);
                        for (Definition def : mocks) {
                            if (doReset && def instanceof Resettable) {
                                ((Resettable) def).reset();
                            }
                            registry.addLocalDef(def);
                        }
                    }
                }
            } else {
                testContextAdapter.clear();
            }
        }
    }

    return context;
}

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);//w w w  .j ava 2 s . c  o  m
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

From source file:org.fao.geonet.api.groups.GroupsApi.java

/**
 * Writes the group logo image to the response. If no image is found it
 * writes a 1x1 transparent PNG. If the request contain cache related
 * headers it checks if the resource has changed and return a 304 Not
 * Modified response if not changed.//from www . j a v  a  2s  .co m
 *
 * @param groupId    the group identifier.
 * @param webRequest the web request.
 * @param request    the native HTTP Request.
 * @param response   the servlet response.
 * @throws ResourceNotFoundException if no group exists with groupId.
 */
@ApiOperation(value = "Get the group logo image.", nickname = "get", notes = API_GET_LOGO_NOTE)
@RequestMapping(value = "/{groupId}/logo", method = RequestMethod.GET)
public void getGroupLogo(
        @ApiParam(value = "Group identifier", required = true) @PathVariable(value = "groupId") final Integer groupId,
        @ApiIgnore final WebRequest webRequest, HttpServletRequest request, HttpServletResponse response)
        throws ResourceNotFoundException {

    Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());

    ApplicationContext context = ApplicationContextHolder.get();
    ServiceContext serviceContext = ApiUtils.createServiceContext(request, locale.getISO3Country());
    if (context == null) {
        throw new RuntimeException("ServiceContext not available");
    }

    GroupRepository groupRepository = context.getBean(GroupRepository.class);

    Group group = groupRepository.findOne(groupId);
    if (group == null) {
        throw new ResourceNotFoundException(
                messages.getMessage("api.groups.group_not_found", new Object[] { groupId }, locale));
    }
    try {
        final Path logosDir = Resources.locateLogosDir(serviceContext);
        final Path harvesterLogosDir = Resources.locateHarvesterLogosDir(serviceContext);
        final String logoUUID = group.getLogo();
        Path imagePath = null;
        FileTime lastModifiedTime = null;
        if (StringUtils.isNotBlank(logoUUID) && !logoUUID.startsWith("http://")
                && !logoUUID.startsWith("https//")) {
            imagePath = Resources.findImagePath(logoUUID, logosDir);
            if (imagePath == null) {
                imagePath = Resources.findImagePath(logoUUID, harvesterLogosDir);
            }
            if (imagePath != null) {
                lastModifiedTime = Files.getLastModifiedTime(imagePath);
                if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                    // webRequest.checkNotModified sets the right HTTP headers
                    response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);

                    return;
                }
                response.setContentType(AttachmentsApi.getFileContentType(imagePath));
                response.setContentLength((int) Files.size(imagePath));
                response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
                response.setDateHeader("Expires", System.currentTimeMillis() + SIX_HOURS * 1000L);
                FileUtils.copyFile(imagePath.toFile(), response.getOutputStream());
            }
        }

        if (imagePath == null) {
            // no logo image found. Return a transparent 1x1 png
            lastModifiedTime = FileTime.fromMillis(0);
            if (webRequest.checkNotModified(lastModifiedTime.toMillis())) {
                return;
            }
            response.setContentType("image/png");
            response.setContentLength(TRANSPARENT_1_X_1_PNG.length);
            response.addHeader("Cache-Control", "max-age=" + SIX_HOURS + ", public");
            response.getOutputStream().write(TRANSPARENT_1_X_1_PNG);
        }

    } catch (IOException e) {
        Log.error(LOGGER,
                String.format("There was an error accessing the logo of the group with id '%d'", groupId));
        throw new RuntimeException(e);
    }
}

From source file:org.fao.geonet.api.records.editing.MetadataEditingApi.java

/**
 * This is a lightweight representation of the
 * legacy Jeeves XML processed by XSLT. Only
 * element required for the editor are created.
 *//*  www.  ja  va 2s.c o m*/
private Element buildEditorForm(String tab, HttpSession session, Map<String, String> allRequestParams,
        HttpServletRequest request, int id, Element xml, String schema, boolean showValidationErrors,
        ServiceContext context, ApplicationContext applicationContext, boolean isEmbedded, boolean embedded)
        throws Exception {

    UserSession userSession = ApiUtils.getUserSession(session);
    Element root = buildResourceDocument(applicationContext, context, userSession);
    root.addContent(xml);
    Element gui = root.getChild("gui");
    gui.addContent(new Element("currTab").setText(tab));
    // This flag is used to generate top tool bar or not
    gui.addContent(new Element("reqService").setText(embedded ? "embedded" : "md.edit"));
    String iso3langCode = languageUtils.getIso3langCode(request.getLocales());
    gui.addContent(new Element("language").setText(iso3langCode));
    gui.addContent(getSchemaStrings(schema, context));

    Element requestParams = new Element("request");
    for (Map.Entry<String, String> e : allRequestParams.entrySet()) {
        requestParams.addContent(new Element(e.getKey()).setText(e.getValue()));
    }
    root.addContent(requestParams);

    GeonetworkDataDirectory dataDirectory = applicationContext.getBean(GeonetworkDataDirectory.class);
    Path xslt = dataDirectory.getWebappDir()
            .resolve(isEmbedded ? "xslt/ui-metadata/edit/edit-embedded.xsl" : "xslt/ui-metadata/edit/edit.xsl");
    return Xml.transform(root, xslt);
}

From source file:org.fao.geonet.api.records.MetadataApi.java

@ApiOperation(value = "Get record related resources", nickname = "getAssociated", notes = "Retrieve related services, datasets, onlines, thumbnails, sources, ... "
        + "to this records.<br/>"
        + "<a href='http://geonetwork-opensource.org/manuals/trunk/eng/users/user-guide/associating-resources/index.html'>More info</a>")
@RequestMapping(value = "/{metadataUuid}/related", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
@ResponseStatus(HttpStatus.OK)//from   w w  w  .java  2  s . c  o m
@ApiResponses(value = { @ApiResponse(code = 200, message = "Return the associated resources."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW) })
@ResponseBody
public RelatedResponse getRelated(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @ApiParam(value = "Type of related resource. If none, all resources are returned.", required = false) @RequestParam(defaultValue = "") RelatedItemType[] type,
        @ApiParam(value = "Start offset for paging. Default 1. Only applies to related metadata records (ie. not for thumbnails).", required = false) @RequestParam(defaultValue = "1") int start,
        @ApiParam(value = "Number of rows returned. Default 100.") @RequestParam(defaultValue = "100") int rows,
        HttpServletRequest request) throws Exception {

    AbstractMetadata md;
    try {
        md = ApiUtils.canViewRecord(metadataUuid, request);
    } catch (SecurityException e) {
        Log.debug(API.LOG_MODULE_NAME, e.getMessage(), e);
        throw new NotAllowedException(ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW);
    }

    String language = languageUtils.getIso3langCode(request.getLocales());

    // TODO PERF: ByPass XSL processing and create response directly
    // At least for related metadata and keep XSL only for links
    final ServiceContext context = ApiUtils.createServiceContext(request);
    Element raw = new Element("root").addContent(Arrays.asList(
            new Element("gui").addContent(Arrays.asList(new Element("language").setText(language),
                    new Element("url").setText(context.getBaseUrl()))),
            MetadataUtils.getRelated(context, md.getId(), md.getUuid(), type, start, start + rows, true)));
    GeonetworkDataDirectory dataDirectory = context.getBean(GeonetworkDataDirectory.class);
    Path relatedXsl = dataDirectory.getWebappDir().resolve("xslt/services/metadata/relation.xsl");

    final Element transform = Xml.transform(raw, relatedXsl);
    RelatedResponse response = (RelatedResponse) Xml.unmarshall(transform, RelatedResponse.class);
    return response;
}

From source file:org.fao.geonet.api.records.MetadataWorkflowApi.java

@ApiOperation(value = "Get last workflow status for a record", notes = "", nickname = "getStatus")
@RequestMapping(value = "/{metadataUuid}/status/workflow/last", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@PreAuthorize("hasRole('Editor')")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Record status."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_EDIT) })
@ResponseStatus(HttpStatus.OK)//from www.  j a v a 2s  . c  om
@ResponseBody
public MetadataWorkflowStatusResponse getStatus(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        HttpServletRequest request) throws Exception {
    AbstractMetadata metadata = ApiUtils.canEditRecord(metadataUuid, request);
    ApplicationContext appContext = ApplicationContextHolder.get();
    Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());
    ServiceContext context = ApiUtils.createServiceContext(request, locale.getISO3Language());

    AccessManager am = appContext.getBean(AccessManager.class);
    //--- only allow the owner of the record to set its status
    if (!am.isOwner(context, String.valueOf(metadata.getId()))) {
        throw new SecurityException(String.format(
                "Only the owner of the metadata can get the status. User is not the owner of the metadata"));
    }

    IMetadataStatus metadataStatus = context.getBean(IMetadataStatus.class);
    MetadataStatus recordStatus = metadataStatus.getStatus(metadata.getId());

    //        List<StatusValue> elStatus = context.getBean(StatusValueRepository.class).findAll();
    List<StatusValue> elStatus = context.getBean(StatusValueRepository.class)
            .findAllByType(StatusValueType.workflow);

    //--- get the list of content reviewers for this metadata record
    Set<Integer> ids = new HashSet<Integer>();
    ids.add(Integer.valueOf(metadata.getId()));
    List<Pair<Integer, User>> reviewers = context.getBean(UserRepository.class)
            .findAllByGroupOwnerNameAndProfile(ids, Profile.Reviewer, SortUtils.createSort(User_.name));
    List<User> listOfReviewers = new ArrayList<>();
    for (Pair<Integer, User> reviewer : reviewers) {
        listOfReviewers.add(reviewer.two());
    }
    return new MetadataWorkflowStatusResponse(recordStatus, listOfReviewers,
            am.hasEditPermission(context, metadata.getId() + ""), elStatus);

}

From source file:org.fao.geonet.api.records.MetadataWorkflowApi.java

@ApiOperation(value = "Set the record status", notes = "", nickname = "setStatus")
@RequestMapping(value = "/{metadataUuid}/status", method = RequestMethod.PUT)
@PreAuthorize("hasRole('Editor')")
@ApiResponses(value = { @ApiResponse(code = 204, message = "Status updated."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_EDIT) })
@ResponseStatus(HttpStatus.NO_CONTENT)//from  w w  w . j  av  a  2 s .  c  om
public void setStatus(
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @ApiParam(value = "Metadata status", required = true) @RequestBody(required = true) MetadataStatusParameter status,
        HttpServletRequest request) throws Exception {
    AbstractMetadata metadata = ApiUtils.canEditRecord(metadataUuid, request);
    ApplicationContext appContext = ApplicationContextHolder.get();
    ServiceContext context = ApiUtils.createServiceContext(request,
            languageUtils.getIso3langCode(request.getLocales()));

    AccessManager am = appContext.getBean(AccessManager.class);
    //--- only allow the owner of the record to set its status
    if (!am.isOwner(context, String.valueOf(metadata.getId()))) {
        throw new SecurityException(String.format(
                "Only the owner of the metadata can set the status of this record. User is not the owner of the metadata."));
    }

    //--- use StatusActionsFactory and StatusActions class to
    //--- change status and carry out behaviours for status changes
    StatusActionsFactory saf = appContext.getBean(StatusActionsFactory.class);

    StatusActions sa = saf.createStatusActions(context);

    int author = context.getUserSession().getUserIdAsInt();
    MetadataStatus metadataStatus = convertParameter(metadata.getId(), status, author);
    List<MetadataStatus> listOfStatusChange = new ArrayList<>(1);
    listOfStatusChange.add(metadataStatus);
    sa.onStatusChange(listOfStatusChange);

    //--- reindex metadata
    DataManager dataManager = appContext.getBean(DataManager.class);
    dataManager.indexMetadata(String.valueOf(metadata.getId()), true, null);
}

From source file:org.fao.geonet.api.userfeedback.UserFeedbackAPI.java

/**
 * New user feedback.//w  w w .  j  a  v  a 2s  . c om
 *
 * @param userFeedbackDto the user feedback dto
 * @param httpSession the http session
 * @return the response entity
 * @throws Exception the exception
 */
@ApiOperation(value = "Creates a user feedback", notes = "Creates a user feedback in draft status if the user is not logged in.", nickname = "newUserFeedback")
@RequestMapping(value = "/userfeedback", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public ResponseEntity newUserFeedback(@ApiParam(name = "uf") @RequestBody UserFeedbackDTO userFeedbackDto,
        @ApiIgnore final HttpSession httpSession, @ApiIgnore final HttpServletRequest request)
        throws Exception {

    final ApplicationContext appContext = ApplicationContextHolder.get();
    final SettingManager settingManager = appContext.getBean(SettingManager.class);
    final String functionEnabled = settingManager.getValue(Settings.SYSTEM_LOCALRATING_ENABLE);

    if (!functionEnabled.equals(RatingsSetting.ADVANCED)) {
        return new ResponseEntity(HttpStatus.FORBIDDEN);
    }

    try {

        final UserSession session = ApiUtils.getUserSession(httpSession);

        Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());
        ResourceBundle messages = ResourceBundle.getBundle("org.fao.geonet.api.Messages", locale);

        Log.debug("org.fao.geonet.api.userfeedback.UserFeedback", "newUserFeedback");

        final IUserFeedbackService userFeedbackService = getUserFeedbackService();

        boolean recaptchaEnabled = settingManager
                .getValueAsBool(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_ENABLE);

        if (recaptchaEnabled) {
            boolean validRecaptcha = RecaptchaChecker.verify(userFeedbackDto.getCaptcha(),
                    settingManager.getValue(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_SECRETKEY));
            if (!validRecaptcha) {
                return new ResponseEntity<>(messages.getString("recaptcha_not_valid"),
                        HttpStatus.PRECONDITION_FAILED);
            }
        }

        userFeedbackService.saveUserFeedback(UserFeedbackUtils.convertFromDto(userFeedbackDto,
                session != null ? session.getPrincipal() : null), request.getRemoteAddr());

        return new ResponseEntity(HttpStatus.CREATED);
    } catch (final Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.fao.geonet.api.userfeedback.UserFeedbackAPI.java

@ApiOperation(value = "Send an email to catalogue administrator or record's contact", notes = "", nickname = "sendEmailToContact")
@RequestMapping(value = "/records/{metadataUuid}/alert", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)/*from w w  w  .  j  ava 2s . c  o  m*/
@ResponseBody
public ResponseEntity sendEmailToContact(
        @ApiParam(value = "Metadata record UUID.", required = true) @PathVariable(value = "metadataUuid") final String metadataUuid,
        @ApiParam(value = "Recaptcha validation key.", required = false) @RequestParam(required = false, defaultValue = "") final String recaptcha,
        @ApiParam(value = "User name.", required = true) @RequestParam final String name,
        @ApiParam(value = "User organisation.", required = true) @RequestParam final String org,
        @ApiParam(value = "User email address.", required = true) @RequestParam final String email,
        @ApiParam(value = "A comment or question.", required = true) @RequestParam final String comments,
        @ApiParam(value = "User phone number.", required = false) @RequestParam(required = false, defaultValue = "") final String phone,
        @ApiParam(value = "Email subject.", required = false) @RequestParam(required = false, defaultValue = "User feedback") final String subject,
        @ApiParam(value = "User function.", required = false) @RequestParam(required = false, defaultValue = "-") final String function,
        @ApiParam(value = "Comment type.", required = false) @RequestParam(required = false, defaultValue = "-") final String type,
        @ApiParam(value = "Comment category.", required = false) @RequestParam(required = false, defaultValue = "-") final String category,
        @ApiParam(value = "List of record's contact to send this email.", required = false) @RequestParam(required = false, defaultValue = "") final String metadataEmail,
        @ApiIgnore final HttpServletRequest request) throws IOException {
    ConfigurableApplicationContext applicationContext = ApplicationContextHolder.get();
    SettingManager sm = applicationContext.getBean(SettingManager.class);
    MetadataRepository metadataRepository = applicationContext.getBean(MetadataRepository.class);

    Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());
    ResourceBundle messages = ResourceBundle.getBundle("org.fao.geonet.api.Messages", locale);

    boolean recaptchaEnabled = sm.getValueAsBool(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_ENABLE);

    if (recaptchaEnabled) {
        boolean validRecaptcha = RecaptchaChecker.verify(recaptcha,
                sm.getValue(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_SECRETKEY));
        if (!validRecaptcha) {
            return new ResponseEntity<>(messages.getString("recaptcha_not_valid"),
                    HttpStatus.PRECONDITION_FAILED);
        }
    }

    String to = sm.getValue(SYSTEM_FEEDBACK_EMAIL);
    String catalogueName = sm.getValue(SYSTEM_SITE_NAME_PATH);

    List<String> toAddress = new LinkedList<String>();
    toAddress.add(to);
    if (isNotBlank(metadataEmail)) {
        //Check metadata email belongs to metadata security!!
        Metadata md = metadataRepository.findOneByUuid(metadataUuid);
        if (md.getData().indexOf(metadataEmail) > 0) {
            toAddress.add(metadataEmail);
        }
    }

    String title = XslUtil.getIndexField(null, metadataUuid, "title", "");

    MailUtil.sendMail(toAddress,
            String.format(messages.getString("user_feedback_title"), catalogueName, title, subject),
            String.format(messages.getString("user_feedback_text"), name, org, function, email, phone, title,
                    type, category, comments, sm.getNodeURL(), metadataUuid),
            sm);

    return new ResponseEntity(HttpStatus.CREATED);
}