Search in sources :

Example 36 with PreAuthorize

use of org.springframework.security.access.prepost.PreAuthorize in project geode by apache.

the class PdxBasedCrudController method read.

/**
   * Reading data for set of keys
   * 
   * @param region gemfire region name
   * @param keys string containing comma seperated keys
   * @return JSON document
   */
@RequestMapping(method = RequestMethod.GET, value = "/{region}/{keys}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiOperation(value = "read data for specific keys", notes = "Read data for specific set of keys in region.", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "OK."), @ApiResponse(code = 400, message = "Bad Request."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 404, message = "Region does not exist."), @ApiResponse(code = 500, message = "GemFire throws an error or exception.") })
@PreAuthorize("@securityService.authorize('READ', #region, #keys)")
public ResponseEntity<?> read(@PathVariable("region") String region, @PathVariable("keys") final String[] keys, @RequestParam(value = "ignoreMissingKey", required = false) final String ignoreMissingKey) {
    logger.debug("Reading data for keys ({}) in Region ({})", ArrayUtils.toString(keys), region);
    final HttpHeaders headers = new HttpHeaders();
    region = decode(region);
    if (keys.length == 1) {
        /* GET op on single key */
        Object value = getValue(region, keys[0]);
        // if region.get(K) return null (i.e INVLD or TOMBSTONE case) We consider 404, NOT Found case
        if (value == null) {
            throw new ResourceNotFoundException(String.format("Key (%1$s) does not exist for region (%2$s) in cache!", keys[0], region));
        }
        final RegionEntryData<Object> data = new RegionEntryData<>(region);
        headers.set("Content-Location", toUri(region, keys[0]).toASCIIString());
        data.add(value);
        return new ResponseEntity<RegionData<?>>(data, headers, HttpStatus.OK);
    } else {
        // fail fast for the case where ignoreMissingKey param is not specified correctly.
        if (ignoreMissingKey != null && !(ignoreMissingKey.equalsIgnoreCase("true") || ignoreMissingKey.equalsIgnoreCase("false"))) {
            String errorMessage = String.format("ignoreMissingKey param (%1$s) is not valid. valid usage is ignoreMissingKey=true!", ignoreMissingKey);
            return new ResponseEntity<>(convertErrorAsJson(errorMessage), HttpStatus.BAD_REQUEST);
        }
        if (!("true".equalsIgnoreCase(ignoreMissingKey))) {
            List<String> unknownKeys = checkForMultipleKeysExist(region, keys);
            if (unknownKeys.size() > 0) {
                String unknownKeysAsStr = StringUtils.collectionToDelimitedString(unknownKeys, ",");
                String erroString = String.format("Requested keys (%1$s) not exist in region (%2$s)", StringUtils.collectionToDelimitedString(unknownKeys, ","), region);
                return new ResponseEntity<>(convertErrorAsJson(erroString), headers, HttpStatus.BAD_REQUEST);
            }
        }
        final Map<Object, Object> valueObjs = getValues(region, keys);
        // Do we need to remove null values from Map..?
        // To Remove null value entries from map.
        // valueObjs.values().removeAll(Collections.singleton(null));
        // currently we are not removing keys having value null from the result.
        String keyList = StringUtils.collectionToDelimitedString(valueObjs.keySet(), ",");
        headers.set("Content-Location", toUri(region, keyList).toASCIIString());
        final RegionData<Object> data = new RegionData<>(region);
        data.add(valueObjs.values());
        return new ResponseEntity<RegionData<?>>(data, headers, HttpStatus.OK);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) RegionEntryData(org.apache.geode.rest.internal.web.controllers.support.RegionEntryData) RegionData(org.apache.geode.rest.internal.web.controllers.support.RegionData) ResourceNotFoundException(org.apache.geode.rest.internal.web.exception.ResourceNotFoundException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(io.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 37 with PreAuthorize

use of org.springframework.security.access.prepost.PreAuthorize in project geode by apache.

the class QueryAccessController method runNamedQuery.

/**
   * Run named parametrized Query with ID
   * 
   * @param queryId id of the OQL string
   * @param arguments query bind params required while executing query
   * @return query result as a JSON document
   */
@RequestMapping(method = RequestMethod.POST, value = "/{query}", produces = { MediaType.APPLICATION_JSON_VALUE })
@ApiOperation(value = "run parametrized query", notes = "run the specified named query passing in scalar values for query parameters in the GemFire cluster", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "Query successfully executed."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 400, message = "Query bind params specified as JSON document in the request body is invalid"), @ApiResponse(code = 500, message = "GemFire throws an error or exception") })
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("@securityService.authorize('DATA', 'READ')")
public ResponseEntity<String> runNamedQuery(@PathVariable("query") String queryId, @RequestBody String arguments) {
    logger.debug("Running named Query with ID ({})...", queryId);
    queryId = decode(queryId);
    if (arguments != null) {
        // Its a compiled query.
        // Convert arguments into Object[]
        Object[] args = jsonToObjectArray(arguments);
        Query compiledQuery = compiledQueries.get(queryId);
        if (compiledQuery == null) {
            // This is first time the query is seen by this server.
            final String oql = getValue(PARAMETERIZED_QUERIES_REGION, queryId, false);
            ValidationUtils.returnValueThrowOnNull(oql, new ResourceNotFoundException(String.format("No Query with ID (%1$s) was found!", queryId)));
            try {
                compiledQuery = getQueryService().newQuery(oql);
            } catch (QueryInvalidException qie) {
                throw new GemfireRestException("Syntax of the OQL queryString is invalid!", qie);
            }
            compiledQueries.putIfAbsent(queryId, (DefaultQuery) compiledQuery);
        }
        // and handle the Exceptions appropriately (500 Server Error)!
        try {
            Object queryResult = compiledQuery.execute(args);
            return processQueryResponse(compiledQuery, args, queryResult);
        } catch (FunctionDomainException fde) {
            throw new GemfireRestException("A function was applied to a parameter that is improper for that function!", fde);
        } catch (TypeMismatchException tme) {
            throw new GemfireRestException("Bind parameter is not of the expected type!", tme);
        } catch (NameResolutionException nre) {
            throw new GemfireRestException("Name in the query cannot be resolved!", nre);
        } catch (IllegalArgumentException iae) {
            throw new GemfireRestException(" The number of bound parameters does not match the number of placeholders!", iae);
        } catch (IllegalStateException ise) {
            throw new GemfireRestException("Query is not permitted on this type of region!", ise);
        } catch (QueryExecutionTimeoutException qete) {
            throw new GemfireRestException("Query execution time is exceeded  max query execution time (gemfire.Cache.MAX_QUERY_EXECUTION_TIME) configured!", qete);
        } catch (QueryInvocationTargetException qite) {
            throw new GemfireRestException("Data referenced in from clause is not available for querying!", qite);
        } catch (QueryExecutionLowMemoryException qelme) {
            throw new GemfireRestException("Query gets canceled due to low memory conditions and the resource manager critical heap percentage has been set!", qelme);
        } catch (Exception e) {
            throw new GemfireRestException("Error encountered while executing named query!", e);
        }
    } else {
        throw new GemfireRestException(" Bind params either not specified or not processed properly by the server!");
    }
}
Also used : Query(org.apache.geode.cache.query.Query) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) QueryExecutionLowMemoryException(org.apache.geode.cache.query.QueryExecutionLowMemoryException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) QueryExecutionTimeoutException(org.apache.geode.cache.query.QueryExecutionTimeoutException) ResourceNotFoundException(org.apache.geode.rest.internal.web.exception.ResourceNotFoundException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) QueryExecutionLowMemoryException(org.apache.geode.cache.query.QueryExecutionLowMemoryException) GemfireRestException(org.apache.geode.rest.internal.web.exception.GemfireRestException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) GemfireRestException(org.apache.geode.rest.internal.web.exception.GemfireRestException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) QueryExecutionTimeoutException(org.apache.geode.cache.query.QueryExecutionTimeoutException) ResourceNotFoundException(org.apache.geode.rest.internal.web.exception.ResourceNotFoundException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(io.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 38 with PreAuthorize

use of org.springframework.security.access.prepost.PreAuthorize in project dhis2-core by dhis2.

the class EventAnalyticsController method getAggregateJson.

// -------------------------------------------------------------------------
// Aggregate
// -------------------------------------------------------------------------
@PreAuthorize("hasRole('ALL') or hasRole('F_VIEW_EVENT_ANALYTICS')")
@RequestMapping(value = RESOURCE_PATH + "/aggregate/{program}", method = RequestMethod.GET, produces = { "application/json", "application/javascript" })
// JSON, JSONP
@ResponseBody
public // JSON, JSONP
Grid getAggregateJson(@PathVariable String program, @RequestParam(required = false) String stage, @RequestParam(required = false) Date startDate, @RequestParam(required = false) Date endDate, @RequestParam Set<String> dimension, @RequestParam(required = false) Set<String> filter, @RequestParam(required = false) String value, @RequestParam(required = false) AggregationType aggregationType, @RequestParam(required = false) boolean skipMeta, @RequestParam(required = false) boolean skipData, @RequestParam(required = false) boolean skipRounding, @RequestParam(required = false) boolean completedOnly, @RequestParam(required = false) boolean hierarchyMeta, @RequestParam(required = false) boolean showHierarchy, @RequestParam(required = false) SortOrder sortOrder, @RequestParam(required = false) Integer limit, @RequestParam(required = false) EventOutputType outputType, @RequestParam(required = false) EventStatus eventStatus, @RequestParam(required = false) ProgramStatus programStatus, @RequestParam(required = false) boolean collapseDataDimensions, @RequestParam(required = false) boolean aggregateData, @RequestParam(required = false) DisplayProperty displayProperty, @RequestParam(required = false) Date relativePeriodDate, @RequestParam(required = false) String userOrgUnit, DhisApiVersion apiVersion, Model model, HttpServletResponse response) throws Exception {
    EventQueryParams params = eventDataQueryService.getFromUrl(program, stage, startDate, endDate, dimension, filter, value, aggregationType, skipMeta, skipData, skipRounding, completedOnly, hierarchyMeta, showHierarchy, sortOrder, limit, outputType, eventStatus, programStatus, collapseDataDimensions, aggregateData, displayProperty, relativePeriodDate, userOrgUnit, apiVersion);
    contextUtils.configureResponse(response, ContextUtils.CONTENT_TYPE_JSON, CacheStrategy.RESPECT_SYSTEM_SETTING);
    return analyticsService.getAggregatedEventData(params);
}
Also used : EventQueryParams(org.hisp.dhis.analytics.event.EventQueryParams) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 39 with PreAuthorize

use of org.springframework.security.access.prepost.PreAuthorize in project dhis2-core by dhis2.

the class EventAnalyticsController method getAggregateHtml.

@PreAuthorize("hasRole('ALL') or hasRole('F_VIEW_EVENT_ANALYTICS')")
@RequestMapping(value = RESOURCE_PATH + "/aggregate/{program}.html", method = RequestMethod.GET)
public void getAggregateHtml(@PathVariable String program, @RequestParam(required = false) String stage, @RequestParam(required = false) Date startDate, @RequestParam(required = false) Date endDate, @RequestParam Set<String> dimension, @RequestParam(required = false) Set<String> filter, @RequestParam(required = false) String value, @RequestParam(required = false) AggregationType aggregationType, @RequestParam(required = false) boolean skipMeta, @RequestParam(required = false) boolean skipData, @RequestParam(required = false) boolean skipRounding, @RequestParam(required = false) boolean completedOnly, @RequestParam(required = false) boolean hierarchyMeta, @RequestParam(required = false) boolean showHierarchy, @RequestParam(required = false) SortOrder sortOrder, @RequestParam(required = false) Integer limit, @RequestParam(required = false) EventOutputType outputType, @RequestParam(required = false) EventStatus eventStatus, @RequestParam(required = false) ProgramStatus programStatus, @RequestParam(required = false) boolean collapseDataDimensions, @RequestParam(required = false) boolean aggregateData, @RequestParam(required = false) DisplayProperty displayProperty, @RequestParam(required = false) Date relativePeriodDate, @RequestParam(required = false) String userOrgUnit, DhisApiVersion apiVersion, Model model, HttpServletResponse response) throws Exception {
    EventQueryParams params = eventDataQueryService.getFromUrl(program, stage, startDate, endDate, dimension, filter, value, aggregationType, skipMeta, skipData, skipRounding, completedOnly, hierarchyMeta, showHierarchy, sortOrder, limit, outputType, eventStatus, programStatus, collapseDataDimensions, aggregateData, displayProperty, relativePeriodDate, userOrgUnit, apiVersion);
    contextUtils.configureResponse(response, ContextUtils.CONTENT_TYPE_HTML, CacheStrategy.RESPECT_SYSTEM_SETTING, "events.html", false);
    Grid grid = analyticsService.getAggregatedEventData(params);
    GridUtils.toHtml(substituteMetaData(grid), response.getWriter());
}
Also used : EventQueryParams(org.hisp.dhis.analytics.event.EventQueryParams) Grid(org.hisp.dhis.common.Grid) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 40 with PreAuthorize

use of org.springframework.security.access.prepost.PreAuthorize in project dhis2-core by dhis2.

the class EventAnalyticsController method getAggregateCsv.

@PreAuthorize("hasRole('ALL') or hasRole('F_VIEW_EVENT_ANALYTICS')")
@RequestMapping(value = RESOURCE_PATH + "/aggregate/{program}.csv", method = RequestMethod.GET)
public void getAggregateCsv(@PathVariable String program, @RequestParam(required = false) String stage, @RequestParam(required = false) Date startDate, @RequestParam(required = false) Date endDate, @RequestParam Set<String> dimension, @RequestParam(required = false) Set<String> filter, @RequestParam(required = false) String value, @RequestParam(required = false) AggregationType aggregationType, @RequestParam(required = false) boolean skipMeta, @RequestParam(required = false) boolean skipData, @RequestParam(required = false) boolean skipRounding, @RequestParam(required = false) boolean completedOnly, @RequestParam(required = false) boolean hierarchyMeta, @RequestParam(required = false) boolean showHierarchy, @RequestParam(required = false) SortOrder sortOrder, @RequestParam(required = false) Integer limit, @RequestParam(required = false) EventOutputType outputType, @RequestParam(required = false) EventStatus eventStatus, @RequestParam(required = false) ProgramStatus programStatus, @RequestParam(required = false) boolean collapseDataDimensions, @RequestParam(required = false) boolean aggregateData, @RequestParam(required = false) DisplayProperty displayProperty, @RequestParam(required = false) Date relativePeriodDate, @RequestParam(required = false) String userOrgUnit, DhisApiVersion apiVersion, Model model, HttpServletResponse response) throws Exception {
    EventQueryParams params = eventDataQueryService.getFromUrl(program, stage, startDate, endDate, dimension, filter, value, aggregationType, skipMeta, skipData, skipRounding, completedOnly, hierarchyMeta, showHierarchy, sortOrder, limit, outputType, eventStatus, programStatus, collapseDataDimensions, aggregateData, displayProperty, relativePeriodDate, userOrgUnit, apiVersion);
    contextUtils.configureResponse(response, ContextUtils.CONTENT_TYPE_CSV, CacheStrategy.RESPECT_SYSTEM_SETTING, "events.csv", true);
    Grid grid = analyticsService.getAggregatedEventData(params);
    GridUtils.toCsv(substituteMetaData(grid), response.getWriter());
}
Also used : EventQueryParams(org.hisp.dhis.analytics.event.EventQueryParams) Grid(org.hisp.dhis.common.Grid) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)289 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)234 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)88 ApiOperation (io.swagger.annotations.ApiOperation)70 ModelAndView (org.springframework.web.servlet.ModelAndView)51 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)44 ResponseEntity (org.springframework.http.ResponseEntity)41 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)40 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)36 IOException (java.io.IOException)35 ServiceException (org.nhindirect.common.rest.exceptions.ServiceException)34 InputStream (java.io.InputStream)26 Date (java.util.Date)26 ArrayList (java.util.ArrayList)25 ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)23 ConfigurationServiceException (org.nhindirect.config.service.ConfigurationServiceException)21 List (java.util.List)17 HttpHeaders (org.springframework.http.HttpHeaders)16 Grid (org.hisp.dhis.common.Grid)14 SearchDomainForm (org.nhindirect.config.ui.form.SearchDomainForm)14