Example usage for org.springframework.web.context.request NativeWebRequest getNativeRequest

List of usage examples for org.springframework.web.context.request NativeWebRequest getNativeRequest

Introduction

In this page you can find the example usage for org.springframework.web.context.request NativeWebRequest getNativeRequest.

Prototype

@Nullable
<T> T getNativeRequest(@Nullable Class<T> requiredType);

Source Link

Document

Return the underlying native request object, if available.

Usage

From source file:architecture.ee.web.community.spring.controller.CommunityDataController.java

@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SITE_ADMIN' , 'ROLE_USER')")
@RequestMapping(value = "/pages/list.json", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody/*w ww .  j a va2  s.  co  m*/
public PageList getPageList(
        @RequestParam(value = "objectType", defaultValue = "2", required = false) Integer objectType,
        @RequestParam(value = "state", defaultValue = "NONE", required = false) String state,
        @RequestParam(value = "startIndex", defaultValue = "0", required = false) Integer startIndex,
        @RequestParam(value = "pageSize", defaultValue = "15", required = false) Integer pageSize,
        @RequestParam(value = "full", defaultValue = "true", required = false) Boolean isFull,
        NativeWebRequest request) throws NotFoundException {

    User user = SecurityHelper.getUser();
    long objectId = user.getUserId();
    if (objectType == 1) {
        objectId = user.getCompanyId();
    } else if (objectType == 30) {
        objectId = WebSiteUtils.getWebSite(request.getNativeRequest(HttpServletRequest.class)).getWebSiteId();
    }

    PageState pageState = PageState.valueOf(state.toUpperCase());
    return getPageList(objectType, objectId, pageState, startIndex, pageSize, isFull);
}

From source file:architecture.ee.web.community.spring.controller.CommunityDataController.java

/** ======================================== **/

private long getObjectId(int objectType, User user, NativeWebRequest request) {
    long objectId = 0;
    if (objectType == 1) {
        objectId = user.getCompanyId();/*www  .  j ava  2 s .co  m*/
    } else if (objectType == 2) {
        objectId = user.getUserId();
    } else if (objectType == 30) {
        try {
            objectId = WebSiteUtils.getWebSite(request.getNativeRequest(HttpServletRequest.class))
                    .getWebSiteId();
        } catch (WebSiteNotFoundException e) {
        }
    }
    return objectId;
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

@RequestMapping(value = { "/api/records/{metadataUuid}/formatters/{formatterId}",
        "/api/" + API.VERSION_0_1
                + "/records/{metadataUuid}/formatters/{formatterId}" }, method = RequestMethod.GET, produces = {
                        MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XHTML_XML_VALUE, "application/pdf",
                        MediaType.ALL_VALUE
        // TODO: PDF
})
@ApiOperation(value = "Get a formatted metadata record", nickname = "getRecordFormattedBy")
@ResponseBody// ww  w.  ja  va 2s.  c o m
public void getRecordFormattedBy(
        @ApiParam(value = "Formatter type to use.") @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = MediaType.TEXT_HTML_VALUE) String acceptHeader,
        @PathVariable(value = "formatterId") final String formatterId,
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @RequestParam(value = "width", defaultValue = "_100") final FormatterWidth width,
        @RequestParam(value = "mdpath", required = false) final String mdPath,
        @RequestParam(value = "output", required = false) FormatType formatType,
        @ApiIgnore final NativeWebRequest request, final HttpServletRequest servletRequest) throws Exception {

    ApplicationContext applicationContext = ApplicationContextHolder.get();
    Locale locale = languageUtils.parseAcceptLanguage(servletRequest.getLocales());

    // TODO :
    // if text/html > xsl_view
    // if application/pdf > xsl_view and PDF output
    // if application/x-gn-<formatterId>+(xml|html|pdf|text)
    // Force PDF ouutput when URL parameter is set.
    // This is useful when making GET link to PDF which
    // can not use headers.
    if (MediaType.ALL_VALUE.equals(acceptHeader)) {
        acceptHeader = MediaType.TEXT_HTML_VALUE;
    }
    if (formatType == null) {
        formatType = FormatType.find(acceptHeader);
    }
    if (formatType == null) {
        formatType = FormatType.xml;
    }

    final String language = LanguageUtils.locale2gnCode(locale.getISO3Language());
    final ServiceContext context = createServiceContext(language, formatType,
            request.getNativeRequest(HttpServletRequest.class));
    AbstractMetadata metadata = ApiUtils.canViewRecord(metadataUuid, servletRequest);

    Boolean hideWithheld = true;
    //        final boolean hideWithheld = Boolean.TRUE.equals(hide_withheld) ||
    //            !context.getBean(AccessManager.class).canEdit(context, resolvedId);
    Key key = new Key(metadata.getId(), language, formatType, formatterId, hideWithheld, width);
    final boolean skipPopularityBool = false;

    ISODate changeDate = metadata.getDataInfo().getChangeDate();

    Validator validator;
    if (changeDate != null) {
        final long changeDateAsTime = changeDate.toDate().getTime();
        long roundedChangeDate = changeDateAsTime / 1000 * 1000;
        if (request.checkNotModified(language, roundedChangeDate)
                && context.getBean(CacheConfig.class).allowCaching(key)) {
            if (!skipPopularityBool) {
                context.getBean(DataManager.class).increasePopularity(context,
                        String.valueOf(metadata.getId()));
            }
            return;
        }
        validator = new ChangeDateValidator(changeDateAsTime);
    } else {
        validator = new NoCacheValidator();
    }
    final FormatMetadata formatMetadata = new FormatMetadata(context, key, request);

    byte[] bytes;
    if (hasNonStandardParameters(request)) {
        // the http headers can cause a formatter to output custom output due to the parameters.
        // because it is not known how the parameters may affect the output then we have two choices
        // 1. make a unique cache for each configuration of parameters
        // 2. don't cache anything that has extra parameters beyond the standard parameters used to
        //    create the key
        // #1 has a major flaw because an attacker could simply make new requests always changing the parameters
        // and completely swamp the cache.  So we go with #2.  The formatters are pretty fast so it is a fine solution
        bytes = formatMetadata.call().data;
    } else {
        bytes = context.getBean(FormatterCache.class).get(key, validator, formatMetadata, false);
    }
    if (bytes != null) {
        if (!skipPopularityBool) {
            context.getBean(DataManager.class).increasePopularity(context, String.valueOf(metadata.getId()));
        }
        writeOutResponse(context, metadataUuid, locale.getISO3Language(),
                request.getNativeResponse(HttpServletResponse.class), formatType, bytes);
    }
}

From source file:architecture.ee.web.community.spring.controller.CommunityDataController.java

/**
 * URL  ?  ./*  www . java2 s .c o m*/
 * 
 * @param uploader
 * @param request
 * @return
 * @throws NotFoundException
 * @throws IOException
 */
@RequestMapping(value = "/images/upload_by_url.json", method = RequestMethod.POST)
@ResponseBody
public Image uploadImageByUrl(@RequestBody UrlImageUploader uploader, NativeWebRequest request)
        throws NotFoundException, IOException {

    User user = SecurityHelper.getUser();
    int objectType = uploader.getObjectType();
    long objectId = uploader.getObjectId();
    if (objectType == 2) {
        objectId = user.getUserId();
    } else if (objectType == 1) {
        objectId = user.getCompanyId();
    } else if (objectType == 30) {
        objectId = WebSiteUtils.getWebSite(request.getNativeRequest(HttpServletRequest.class)).getWebSiteId();
    }

    Image imageToUse = imageManager.createImage(objectType, objectId, uploader.getFileName(),
            uploader.getContentType(), uploader.readFileFromUrl());
    imageToUse.setUser(user);
    if (uploader.getSourceUrl() == null) {
        uploader.setSourceUrl(uploader.getImageUrl());
    }
    imageToUse.getProperties().put("source", uploader.getSourceUrl().toString());
    imageToUse.getProperties().put("url", uploader.getImageUrl().toString());

    log.debug(imageToUse);

    return imageManager.saveImage(imageToUse);
}

From source file:architecture.ee.web.community.spring.controller.CommunityDataController.java

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/announce/update.json", method = RequestMethod.POST)
@ResponseBody/*from   w w w .j a  v  a 2s.  c om*/
public Announce saveAnnounce(@RequestBody DefaultAnnounce announce, NativeWebRequest request)
        throws AnnounceNotFoundException, WebSiteNotFoundException {
    User user = SecurityHelper.getUser();
    if (announce.getUser() == null && announce.getAnnounceId() == 0)
        announce.setUser(user);

    if (user.isAnonymous() || user.getUserId() != announce.getUser().getUserId())
        throw new UnAuthorizedException();

    Announce target;
    if (announce.getAnnounceId() > 0) {
        target = announceManager.getAnnounce(announce.getAnnounceId());
    } else {
        if (announce.getObjectType() == 30 && announce.getObjectId() == 0L) {
            announce.setObjectId(
                    WebSiteUtils.getWebSite(request.getNativeRequest(HttpServletRequest.class)).getWebSiteId());
        } else if (announce.getObjectType() == 1 && announce.getObjectId() == 0L) {
            announce.setObjectId(user.getCompanyId());
        }
        target = announceManager.createAnnounce(user, announce.getObjectType(), announce.getObjectId());
    }

    target.setSubject(announce.getSubject());
    target.setBody(announce.getBody());
    target.setStartDate(announce.getStartDate());
    target.setEndDate(announce.getEndDate());
    if (target.getAnnounceId() > 0) {
        announceManager.updateAnnounce(target);
    } else {
        announceManager.addAnnounce(target);
    }
    return target;
}

From source file:architecture.ee.web.community.spring.controller.CommunityDataController.java

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/pages/update.json", method = RequestMethod.POST)
@ResponseBody/*from w  w w  .  j av a2  s.  c o  m*/
public Page updatePage(@RequestBody DefaultPage page, NativeWebRequest request) throws NotFoundException {
    User user = SecurityHelper.getUser();
    if (page.getUser() == null && page.getPageId() == 0)
        page.setUser(user);

    if (user.isAnonymous() || user.getUserId() != page.getUser().getUserId())
        throw new UnAuthorizedException();

    boolean doUpdate = false;
    Page target;
    String tagsString = null;

    log.debug("page:" + page.getProperties());

    if (page.getPageId() > 0) {
        target = pageManager.getPage(page.getPageId());
        if (!StringUtils.equals(page.getName(), target.getName())
                || !StringUtils.equals(page.getTitle(), target.getTitle())
                || !StringUtils.equals(page.getSummary(), target.getSummary()) ||

                !StringUtils.equals(page.getBodyContent().getBodyText(),
                        target.getBodyContent().getBodyText())) {
            // target.setProperties(page.getProperties());

        }
        doUpdate = true;
        log.debug("do update ...");
    } else {
        if (page.getObjectType() == 30 && page.getObjectId() == 0L) {
            page.setObjectId(
                    WebSiteUtils.getWebSite(request.getNativeRequest(HttpServletRequest.class)).getWebSiteId());
        } else if (page.getObjectType() == 1 && page.getObjectId() == 0L) {
            page.setObjectId(user.getCompanyId());
        } else if (page.getObjectType() == 2 && page.getObjectId() == 0L) {
            page.setObjectId(user.getUserId());

        }
        target = new DefaultPage(page.getObjectType(), page.getObjectId());
        target.setUser(page.getUser());
        target.setBodyContent(new DefaultBodyContent());
        // target.setProperties(page.getProperties());
        doUpdate = true;
    }

    tagsString = page.getProperty("tagsString", null);
    if (tagsString != null)
        page.getProperties().remove("tagsString");

    if (doUpdate) {
        target.setName(page.getName());
        target.setTitle(page.getTitle());
        target.setSummary(page.getSummary());
        target.setBodyText(page.getBodyContent().getBodyText());
        target.setProperties(page.getProperties());
        pageManager.updatePage(target);
    }

    if (tagsString != null && !StringUtils.equals(target.getTagDelegator().getTagsAsString(), tagsString))
        target.getTagDelegator().setTags(tagsString);

    log.debug("input:" + page.getProperties());
    log.debug("target:" + target.getProperties());

    return pageManager.getPage(target.getPageId());
}

From source file:org.fao.geonet.services.inspireatom.AtomPredefinedFeed.java

/**
 * Main entry point for local service ATOM feed description
 *
 * @param language the language to be used for translation of title, etc. in the resulting service ATOM feed
 * @param uuid identifier of the metadata of service (this could be made optional once a system-wide top level metadata could be set)
 *//*from  www  .jav  a  2  s  .co m*/
@RequestMapping(value = "/" + InspireAtomUtil.LOCAL_DESCRIBE_SERVICE_URL_SUFFIX)
@ResponseBody
public HttpEntity<byte[]> localServiceDescribe(@RequestParam("uuid") String uuid,
        @RequestParam(value = "language", required = false) String language, NativeWebRequest webRequest)
        throws Exception {

    ServiceContext context = createServiceContext(Geonet.DEFAULT_LANGUAGE,
            webRequest.getNativeRequest(HttpServletRequest.class));

    SettingManager sm = context.getBean(SettingManager.class);
    boolean inspireEnable = sm.getValueAsBool(Settings.SYSTEM_INSPIRE_ENABLE);
    if (!inspireEnable) {
        Log.info(Geonet.ATOM, "INSPIRE is disabled");
        throw new OperationNotAllowedEx("INSPIRE option is not enabled on this catalog.");
    }

    Element feed = getServiceFeed(context, uuid, language);
    return writeOutResponse(Xml.getString(feed), "application", "atom+xml");
}

From source file:org.fao.geonet.services.inspireatom.AtomPredefinedFeed.java

/**
 * Main entry point for local dataset ATOM feed description.
 *
 * @param spIdentifier the spatial dataset identifier
 * @param spNamespace the spatial dataset namespace (not used for the moment)
 * @param language the language to be used for translation of title, etc. in the resulting dataset ATOM feed
 * @param q the searchTerms for filtering of the spatial datasets
 * @param webRequest the request object/*w ww . ja v  a 2  s .co  m*/
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/" + InspireAtomUtil.LOCAL_DESCRIBE_DATASET_URL_SUFFIX)
@ResponseBody
public HttpEntity<byte[]> localDatasetDescribe(
        @RequestParam("spatial_dataset_identifier_code") String spIdentifier,
        @RequestParam(value = "spatial_dataset_identifier_namespace", required = false) String spNamespace,
        @RequestParam(value = "language", required = false) String language,
        @RequestParam(value = "q", required = false) String searchTerms, NativeWebRequest webRequest)
        throws Exception {
    ServiceContext context = createServiceContext("eng", webRequest.getNativeRequest(HttpServletRequest.class));

    SettingManager sm = context.getBean(SettingManager.class);
    boolean inspireEnable = sm.getValueAsBool(Settings.SYSTEM_INSPIRE_ENABLE);
    if (!inspireEnable) {
        Log.info(Geonet.ATOM, "INSPIRE is disabled");
        throw new OperationNotAllowedEx("INSPIRE option is not enabled on this catalog.");
    }

    Map<String, Object> params = getDefaultXSLParams(sm, context,
            XslUtil.twoCharLangCode(context.getLanguage()));
    if (StringUtils.isNotBlank(searchTerms)) {
        params.put("searchTerms", searchTerms.toLowerCase());
    }
    Element feed = InspireAtomUtil.getDatasetFeed(context, spIdentifier, spNamespace, params, language);
    return writeOutResponse(Xml.getString(feed), "application", "atom+xml");
}

From source file:org.fao.geonet.services.inspireatom.AtomPredefinedFeed.java

/**
 * Main entry point for local dataset ATOM feed download.
 *
 * @param spIdentifier the spatial dataset identifier
 * @param spNamespace the spatial dataset namespace (not used for the moment)
 * @param crs the crs of the dataset//from  w  ww .ja  v a 2 s.  c  o  m
 * @param language the language to be used for translation of title, etc. in the resulting dataset ATOM feed
 * @param q the searchTerms for filtering of the spatial datasets
 * @param webRequest the request object
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/" + InspireAtomUtil.LOCAL_DOWNLOAD_DATASET_URL_SUFFIX)
@ResponseBody
public HttpEntity<byte[]> localDatasetDownload(
        @RequestParam("spatial_dataset_identifier_code") String spIdentifier,
        @RequestParam(value = "spatial_dataset_identifier_namespace", required = false) String spNamespace,
        @RequestParam(value = "crs", required = false) String crs,
        @RequestParam(value = "language", required = false) String language,
        @RequestParam(value = "q", required = false) String searchTerms, NativeWebRequest webRequest)
        throws Exception {
    ServiceContext context = createServiceContext(Geonet.DEFAULT_LANGUAGE,
            webRequest.getNativeRequest(HttpServletRequest.class));

    SettingManager sm = context.getBean(SettingManager.class);
    boolean inspireEnable = sm.getValueAsBool(Settings.SYSTEM_INSPIRE_ENABLE);
    if (!inspireEnable) {
        Log.info(Geonet.ATOM, "INSPIRE is disabled");
        throw new OperationNotAllowedEx("INSPIRE option is not enabled on this catalog.");
    }

    Map<String, Object> params = getDefaultXSLParams(sm, context, context.getLanguage());
    if (StringUtils.isNotBlank(crs)) {
        crs = URLDecoder.decode(crs, Constants.ENCODING);
        params.put("requestedCrs", crs);
    }
    if (StringUtils.isNotBlank(searchTerms)) {
        params.put("searchTerms", searchTerms.toLowerCase());
    }
    Element feed = InspireAtomUtil.getDatasetFeed(context, spIdentifier, spNamespace, params, language);
    Map<Integer, Element> crsCounts = new HashMap<Integer, Element>();
    ;
    Namespace ns = Namespace.getNamespace("http://www.w3.org/2005/Atom");
    if (crs != null) {
        crsCounts = countDatasetsForCrs(feed, crs, ns);
    } else {
        List<Element> entries = (feed.getChildren("entry", ns));
        if (entries.size() == 1) {
            crsCounts.put(1, entries.get(0));
        }
    }
    int downloadCount = crsCounts.size() > 0 ? crsCounts.keySet().iterator().next() : 0;
    Element selectedEntry = crsCounts.get(downloadCount);

    // No download  for the CRS specified
    if (downloadCount == 0) {
        throw new Exception("No downloads available for dataset (spatial_dataset_identifier_code: "
                + spIdentifier + ", spatial_dataset_identifier_namespace: " + spNamespace + ", crs: " + crs
                + ", searchTerms: " + searchTerms + ")");

        // Only one download for the CRS specified
    } else if (downloadCount == 1) {
        String type = null;
        Element link = selectedEntry.getChild("link", ns);
        if (link != null) {
            type = link.getAttributeValue("type");
        }
        HttpServletResponse nativeRes = webRequest.getNativeResponse(HttpServletResponse.class);
        nativeRes.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        //            nativeRes.setHeader("Location", selectedEntry.getChildText("id",ns));
        return redirectResponse(selectedEntry.getChildText("id", ns));
        // Otherwise, return a feed with the downloads for the specified CRS
    } else {
        // Filter the dataset feed by CRS code.
        InspireAtomUtil.filterDatasetFeedByCrs(feed, crs);
        return writeOutResponse(Xml.getString(feed), "application", "atom+xml");
    }
}

From source file:org.fao.geonet.services.inspireatom.AtomPredefinedFeed.java

/**
 * Main entry point for local open search description
 *
 * @param language the language to be used for translation of title, etc. in the resulting opensearchdescription
 * @param uuid identifier of the metadata of service (this could be made optional once a system-wide top level metadata could be set)
 *///w w  w.ja  va 2 s.c  o  m
@RequestMapping(value = "/" + InspireAtomUtil.LOCAL_OPENSEARCH_URL_SUFFIX + "/"
        + InspireAtomUtil.LOCAL_OPENSEARCH_DESCRIPTION_FILE_NAME)
@ResponseBody
public HttpEntity<byte[]> localOpenSearchDescription(@RequestParam("uuid") String uuid,
        @RequestParam(value = "language", required = false) String language, NativeWebRequest webRequest)
        throws Exception {

    ServiceContext context = createServiceContext(Geonet.DEFAULT_LANGUAGE,
            webRequest.getNativeRequest(HttpServletRequest.class));

    SettingManager sm = context.getBean(SettingManager.class);
    boolean inspireEnable = sm.getValueAsBool(Settings.SYSTEM_INSPIRE_ENABLE);
    if (!inspireEnable) {
        Log.info(Geonet.ATOM, "INSPIRE is disabled");
        throw new OperationNotAllowedEx("INSPIRE option is not enabled on this catalog.");
    }

    Element description = getOpenSearchDescription(context, uuid);
    return writeOutResponse(Xml.getString(description), "application", "opensearchdescription+xml");
}