Search in sources :

Example 1 with RSQLParserException

use of cz.jirutka.rsql.parser.RSQLParserException in project molgenis by molgenis.

the class RestController method retrieveEntityCollection.

/**
 * Does a rsql/fiql query, returns the result as csv
 * <p>
 * Parameters:
 * <p>
 * q: the query
 * <p>
 * attributes: the attributes to return, if not specified returns all attributes
 * <p>
 * start: the index of the first row, default 0
 * <p>
 * num: the number of results to return, default 100, max 10000
 * <p>
 * <p>
 * Example: /api/v1/csv/person?q=firstName==Piet&attributes=firstName,lastName&start=10&num=100
 */
@GetMapping(value = "/csv/{entityTypeId}", produces = "text/csv")
@ResponseBody
public EntityCollection retrieveEntityCollection(@PathVariable("entityTypeId") String entityTypeId, @RequestParam(value = "attributes", required = false) String[] attributes, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final Set<String> attributesSet = toAttributeSet(attributes);
    EntityType meta;
    Iterable<Entity> entities;
    try {
        meta = dataService.getEntityType(entityTypeId);
        Query<Entity> q = new QueryStringParser(meta, molgenisRSQL).parseQueryString(req.getParameterMap());
        String[] sortAttributeArray = req.getParameterMap().get("sortColumn");
        if (sortAttributeArray != null && sortAttributeArray.length == 1 && StringUtils.isNotEmpty(sortAttributeArray[0])) {
            String sortAttribute = sortAttributeArray[0];
            String[] sortOrderArray = req.getParameterMap().get("sortOrder");
            Sort.Direction order = Sort.Direction.ASC;
            if (sortOrderArray != null && sortOrderArray.length == 1 && StringUtils.isNotEmpty(sortOrderArray[0])) {
                String sortOrder = sortOrderArray[0];
                switch(sortOrder) {
                    case "ASC":
                        order = Sort.Direction.ASC;
                        break;
                    case "DESC":
                        order = Sort.Direction.DESC;
                        break;
                    default:
                        throw new RuntimeException("unknown sort order");
                }
            }
            q.sort().on(sortAttribute, order);
        }
        if (q.getPageSize() == 0) {
            q.pageSize(EntityCollectionRequest.DEFAULT_ROW_COUNT);
        }
        if (q.getPageSize() > EntityCollectionRequest.MAX_ROWS) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Num exceeded the maximum of " + EntityCollectionRequest.MAX_ROWS + " rows");
            return null;
        }
        entities = () -> dataService.findAll(entityTypeId, q).iterator();
    } catch (ConversionFailedException | RSQLParserException | UnknownAttributeException | IllegalArgumentException | UnsupportedOperationException | UnknownEntityException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return null;
    } catch (MolgenisDataAccessException e) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }
    // Check attribute names
    Iterable<String> attributesIterable = Iterables.transform(meta.getAtomicAttributes(), attribute -> attribute.getName().toLowerCase());
    if (attributesSet != null) {
        SetView<String> diff = Sets.difference(attributesSet, Sets.newHashSet(attributesIterable));
        if (!diff.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown attributes " + diff);
            return null;
        }
    }
    attributesIterable = Iterables.transform(meta.getAtomicAttributes(), Attribute::getName);
    if (attributesSet != null) {
        attributesIterable = Iterables.filter(attributesIterable, attribute -> attributesSet.contains(attribute.toLowerCase()));
    }
    return new DefaultEntityCollection(entities, attributesIterable);
}
Also used : UnknownTokenException(org.molgenis.security.core.token.UnknownTokenException) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) RestService(org.molgenis.data.rest.service.RestService) ErrorMessageResponse(org.molgenis.web.ErrorMessageResponse) LoggerFactory(org.slf4j.LoggerFactory) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) RunAsSystemAspect.runAsSystem(org.molgenis.security.core.runas.RunAsSystemAspect.runAsSystem) ENFORCED(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationSetting.ENFORCED) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(org.molgenis.data.meta.model.Attribute) AuthenticationSettings(org.molgenis.security.settings.AuthenticationSettings) Valid(javax.validation.Valid) User(org.molgenis.data.security.auth.User) Matcher(java.util.regex.Matcher) ObjectError(org.springframework.validation.ObjectError) USER(org.molgenis.data.security.auth.UserMetaData.USER) AuthenticationException(org.springframework.security.core.AuthenticationException) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) DefaultEntityCollection(org.molgenis.data.support.DefaultEntityCollection) org.molgenis.data(org.molgenis.data) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) UserAccountService(org.molgenis.security.user.UserAccountService) ConversionException(org.springframework.core.convert.ConversionException) Instant(java.time.Instant) EntityType(org.molgenis.data.meta.model.EntityType) Sets(com.google.common.collect.Sets) UserPermissionEvaluator(org.molgenis.security.core.UserPermissionEvaluator) LocalDate(java.time.LocalDate) MolgenisRSQL(org.molgenis.core.ui.data.rsql.MolgenisRSQL) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Entry(java.util.Map.Entry) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Pattern(java.util.regex.Pattern) Authentication(org.springframework.security.core.Authentication) UserMetaData(org.molgenis.data.security.auth.UserMetaData) Iterables(com.google.common.collect.Iterables) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) java.util(java.util) ENABLED(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationSetting.ENABLED) TokenParam(org.molgenis.security.token.TokenParam) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) QueryImpl(org.molgenis.data.support.QueryImpl) RSQLParserException(cz.jirutka.rsql.parser.RSQLParserException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) EntityUtils.getTypedValue(org.molgenis.data.util.EntityUtils.getTypedValue) Objects.requireNonNull(java.util.Objects.requireNonNull) Href(org.molgenis.core.ui.data.support.Href) ATTRIBUTE_META_DATA(org.molgenis.data.meta.model.AttributeMetadata.ATTRIBUTE_META_DATA) BASE_URI(org.molgenis.data.rest.RestController.BASE_URI) AttributeType(org.molgenis.data.meta.AttributeType) Logger(org.slf4j.Logger) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) SetView(com.google.common.collect.Sets.SetView) IOException(java.io.IOException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) ErrorMessage(org.molgenis.web.ErrorMessageResponse.ErrorMessage) HttpStatus(org.springframework.http.HttpStatus) TokenService(org.molgenis.security.core.token.TokenService) MultipartFile(org.springframework.web.multipart.MultipartFile) Transactional(org.springframework.transaction.annotation.Transactional) DefaultEntityCollection(org.molgenis.data.support.DefaultEntityCollection) RSQLParserException(cz.jirutka.rsql.parser.RSQLParserException) EntityType(org.molgenis.data.meta.model.EntityType) ConversionFailedException(org.springframework.core.convert.ConversionFailedException)

Aggregations

Iterables (com.google.common.collect.Iterables)1 Lists (com.google.common.collect.Lists)1 Sets (com.google.common.collect.Sets)1 SetView (com.google.common.collect.Sets.SetView)1 RSQLParserException (cz.jirutka.rsql.parser.RSQLParserException)1 IOException (java.io.IOException)1 Instant (java.time.Instant)1 LocalDate (java.time.LocalDate)1 java.util (java.util)1 Entry (java.util.Map.Entry)1 Objects.requireNonNull (java.util.Objects.requireNonNull)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Valid (javax.validation.Valid)1 StringUtils (org.apache.commons.lang3.StringUtils)1 MolgenisRSQL (org.molgenis.core.ui.data.rsql.MolgenisRSQL)1 Href (org.molgenis.core.ui.data.support.Href)1 org.molgenis.data (org.molgenis.data)1