Search in sources :

Example 1 with BASE_URI

use of org.molgenis.data.rest.v2.RestControllerV2.BASE_URI in project molgenis by molgenis.

the class RestControllerV2 method createEntityCollectionResponse.

private EntityCollectionResponseV2 createEntityCollectionResponse(String entityTypeId, EntityCollectionRequestV2 request, HttpServletRequest httpRequest, boolean includeCategories) {
    EntityType meta = dataService.getEntityType(entityTypeId);
    Query<Entity> q = request.getQ() != null ? request.getQ().createQuery(meta) : new QueryImpl<>();
    q.pageSize(request.getNum()).offset(request.getStart()).sort(request.getSort());
    Fetch fetch = AttributeFilterToFetchConverter.convert(request.getAttrs(), meta, LocaleContextHolder.getLocale().getLanguage());
    if (fetch != null) {
        q.fetch(fetch);
    }
    if (request.getAggs() != null) {
        // return aggregates for aggregate query
        AggregateQuery aggsQ = request.getAggs().createAggregateQuery(meta, q);
        Attribute xAttr = aggsQ.getAttributeX();
        Attribute yAttr = aggsQ.getAttributeY();
        if (xAttr == null && yAttr == null) {
            throw new MolgenisQueryException("Aggregate query is missing 'x' or 'y' attribute");
        }
        AggregateResult aggs = dataService.aggregate(entityTypeId, aggsQ);
        AttributeResponseV2 xAttrResponse = xAttr != null ? new AttributeResponseV2(entityTypeId, meta, xAttr, fetch, permissionService, dataService) : null;
        AttributeResponseV2 yAttrResponse = yAttr != null ? new AttributeResponseV2(entityTypeId, meta, yAttr, fetch, permissionService, dataService) : null;
        return new EntityAggregatesResponse(aggs, xAttrResponse, yAttrResponse, BASE_URI + '/' + entityTypeId);
    } else {
        Long count = dataService.count(entityTypeId, new QueryImpl<>(q).setOffset(0).setPageSize(0));
        Iterable<Entity> it;
        if (count > 0 && q.getPageSize() > 0) {
            it = () -> dataService.findAll(entityTypeId, q).iterator();
        } else {
            it = Collections.emptyList();
        }
        EntityPager pager = new EntityPager(request.getStart(), request.getNum(), count, it);
        List<Map<String, Object>> entities = new ArrayList<>();
        for (Entity entity : it) {
            Map<String, Object> responseData = new LinkedHashMap<>();
            createEntityValuesResponse(entity, fetch, responseData);
            entities.add(responseData);
        }
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getFullURL(httpRequest));
        String prevHref = null;
        if (pager.getPrevStart() != null) {
            builder.replaceQueryParam("start", pager.getPrevStart());
            prevHref = builder.build(false).toUriString();
        }
        String nextHref = null;
        if (pager.getNextStart() != null) {
            builder.replaceQueryParam("start", pager.getNextStart());
            nextHref = builder.build(false).toUriString();
        }
        return new EntityCollectionResponseV2(pager, entities, fetch, BASE_URI + '/' + entityTypeId, meta, permissionService, dataService, prevHref, nextHref, includeCategories);
    }
}
Also used : Attribute(org.molgenis.data.meta.model.Attribute) AggregateQuery(org.molgenis.data.aggregation.AggregateQuery) EntityType(org.molgenis.data.meta.model.EntityType) AttributeFilterToFetchConverter.createDefaultAttributeFetch(org.molgenis.data.rest.v2.AttributeFilterToFetchConverter.createDefaultAttributeFetch) EntityPager(org.molgenis.data.rest.EntityPager) AggregateResult(org.molgenis.data.aggregation.AggregateResult) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder)

Example 2 with BASE_URI

use of org.molgenis.data.rest.v2.RestControllerV2.BASE_URI in project molgenis by molgenis.

the class RestControllerV2 method createEntityValuesResponseRec.

private void createEntityValuesResponseRec(Entity entity, Iterable<Attribute> attrs, Fetch fetch, Map<String, Object> responseData) {
    responseData.put("_href", Href.concatEntityHref(BASE_URI, entity.getEntityType().getId(), entity.getIdValue()));
    for (// TODO performance use fetch instead of attrs
    Attribute attr : // TODO performance use fetch instead of attrs
    attrs) {
        String attrName = attr.getName();
        if (fetch == null || fetch.hasField(attr)) {
            AttributeType dataType = attr.getDataType();
            switch(dataType) {
                case BOOL:
                    responseData.put(attrName, entity.getBoolean(attrName));
                    break;
                case CATEGORICAL:
                case XREF:
                case FILE:
                    Entity refEntity = entity.getEntity(attrName);
                    Map<String, Object> refEntityResponse;
                    if (refEntity != null) {
                        Fetch refAttrFetch = fetch != null ? fetch.getFetch(attr) : createDefaultAttributeFetch(attr, LanguageService.getCurrentUserLanguageCode());
                        refEntityResponse = createEntityResponse(refEntity, refAttrFetch, false);
                    } else {
                        refEntityResponse = null;
                    }
                    responseData.put(attrName, refEntityResponse);
                    break;
                case CATEGORICAL_MREF:
                case MREF:
                case ONE_TO_MANY:
                    Iterable<Entity> refEntities = entity.getEntities(attrName);
                    List<Map<String, Object>> refEntityResponses;
                    if (refEntities != null) {
                        refEntityResponses = new ArrayList<>();
                        Fetch refAttrFetch = fetch != null ? fetch.getFetch(attrName) : createDefaultAttributeFetch(attr, LanguageService.getCurrentUserLanguageCode());
                        for (Entity refEntitiesEntity : refEntities) {
                            refEntityResponses.add(createEntityResponse(refEntitiesEntity, refAttrFetch, false));
                        }
                    } else {
                        refEntityResponses = null;
                    }
                    responseData.put(attrName, refEntityResponses);
                    break;
                case COMPOUND:
                    throw new RuntimeException("Invalid data type [" + dataType + "]");
                case DATE:
                    LocalDate dateValue = entity.getLocalDate(attrName);
                    responseData.put(attrName, dateValue != null ? dateValue.toString() : null);
                    break;
                case DATE_TIME:
                    Instant dateTimeValue = entity.getInstant(attrName);
                    responseData.put(attrName, dateTimeValue != null ? dateTimeValue.toString() : null);
                    break;
                case DECIMAL:
                    responseData.put(attrName, entity.getDouble(attrName));
                    break;
                case EMAIL:
                case ENUM:
                case HTML:
                case HYPERLINK:
                case SCRIPT:
                case STRING:
                case TEXT:
                    responseData.put(attrName, entity.getString(attrName));
                    break;
                case INT:
                    responseData.put(attrName, entity.getInt(attrName));
                    break;
                case LONG:
                    responseData.put(attrName, entity.getLong(attrName));
                    break;
                default:
                    throw new UnexpectedEnumException(dataType);
            }
        }
    }
}
Also used : Attribute(org.molgenis.data.meta.model.Attribute) Instant(java.time.Instant) LocalDate(java.time.LocalDate) AttributeFilterToFetchConverter.createDefaultAttributeFetch(org.molgenis.data.rest.v2.AttributeFilterToFetchConverter.createDefaultAttributeFetch) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) AttributeType(org.molgenis.data.meta.AttributeType)

Example 3 with BASE_URI

use of org.molgenis.data.rest.v2.RestControllerV2.BASE_URI in project molgenis by molgenis.

the class RestControllerV2 method createEntities.

/**
 * Try to create multiple entities in one transaction. If one fails all fails.
 *
 * @param entityTypeId name of the entity where the entities are going to be added.
 * @param request      EntityCollectionCreateRequestV2
 * @param response     HttpServletResponse
 * @return EntityCollectionCreateResponseBodyV2
 */
@Transactional
@PostMapping(value = "/{entityTypeId}", produces = APPLICATION_JSON_VALUE)
public EntityCollectionBatchCreateResponseBodyV2 createEntities(@PathVariable("entityTypeId") String entityTypeId, @RequestBody @Valid EntityCollectionBatchRequestV2 request, HttpServletResponse response) throws Exception {
    final EntityType meta = dataService.getEntityType(entityTypeId);
    if (meta == null) {
        throw createUnknownEntityException(entityTypeId);
    }
    try {
        final List<Entity> entities = request.getEntities().stream().map(e -> this.restService.toEntity(meta, e)).collect(toList());
        final EntityCollectionBatchCreateResponseBodyV2 responseBody = new EntityCollectionBatchCreateResponseBodyV2();
        final List<String> ids = new ArrayList<>();
        // Add all entities
        if (ATTRIBUTE_META_DATA.equals(entityTypeId)) {
            entities.stream().map(attribute -> (Attribute) attribute).forEach(attribute -> dataService.getMeta().addAttribute(attribute));
        } else {
            this.dataService.add(entityTypeId, entities.stream());
        }
        entities.forEach(entity -> {
            restService.updateMappedByEntities(entity);
            String id = entity.getIdValue().toString();
            ids.add(id);
            responseBody.getResources().add(new AutoValue_ResourcesResponseV2(Href.concatEntityHref(RestControllerV2.BASE_URI, entityTypeId, id)));
        });
        responseBody.setLocation(Href.concatEntityCollectionHref(RestControllerV2.BASE_URI, entityTypeId, meta.getIdAttribute().getName(), ids));
        response.setStatus(HttpServletResponse.SC_CREATED);
        return responseBody;
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        throw e;
    }
}
Also used : EntityType(org.molgenis.data.meta.model.EntityType) LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RestService(org.molgenis.data.rest.service.RestService) RepositoryCopier(org.molgenis.data.support.RepositoryCopier) ErrorMessageResponse(org.molgenis.web.ErrorMessageResponse) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) RunAsSystemAspect.runAsSystem(org.molgenis.security.core.runas.RunAsSystemAspect.runAsSystem) PermissionSystemService(org.molgenis.data.security.permission.PermissionSystemService) Attribute(org.molgenis.data.meta.model.Attribute) TEXT_PLAIN_VALUE(org.springframework.http.MediaType.TEXT_PLAIN_VALUE) Valid(javax.validation.Valid) BASE_URI(org.molgenis.data.rest.v2.RestControllerV2.BASE_URI) EntityTypeIdentity(org.molgenis.data.security.EntityTypeIdentity) Collectors.toSet(java.util.stream.Collectors.toSet) LanguageService(org.molgenis.i18n.LanguageService) org.molgenis.data(org.molgenis.data) EntityTypeUtils(org.molgenis.data.support.EntityTypeUtils) Instant(java.time.Instant) EntityType(org.molgenis.data.meta.model.EntityType) String.format(java.lang.String.format) MEDIUM(java.time.format.FormatStyle.MEDIUM) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) Stream(java.util.stream.Stream) UserPermissionEvaluator(org.molgenis.security.core.UserPermissionEvaluator) LocalDate(java.time.LocalDate) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) EntityPager(org.molgenis.data.rest.EntityPager) java.util(java.util) NameValidator(org.molgenis.data.validation.meta.NameValidator) LocalizationService(org.molgenis.data.i18n.LocalizationService) QueryImpl(org.molgenis.data.support.QueryImpl) Lists.transform(com.google.common.collect.Lists.transform) EntityTypePermission(org.molgenis.data.security.EntityTypePermission) Value(org.springframework.beans.factory.annotation.Value) HttpServletRequest(javax.servlet.http.HttpServletRequest) AggregateResult(org.molgenis.data.aggregation.AggregateResult) EntityUtils.getTypedValue(org.molgenis.data.util.EntityUtils.getTypedValue) Objects.requireNonNull(java.util.Objects.requireNonNull) AttributeFilterToFetchConverter.createDefaultAttributeFetch(org.molgenis.data.rest.v2.AttributeFilterToFetchConverter.createDefaultAttributeFetch) Href(org.molgenis.core.ui.data.support.Href) ATTRIBUTE_META_DATA(org.molgenis.data.meta.model.AttributeMetadata.ATTRIBUTE_META_DATA) AttributeType(org.molgenis.data.meta.AttributeType) Logger(org.slf4j.Logger) AggregateQuery(org.molgenis.data.aggregation.AggregateQuery) StringWriter(java.io.StringWriter) HttpServletResponse(javax.servlet.http.HttpServletResponse) 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) Collectors.toList(java.util.stream.Collectors.toList) DateTimeFormatter(java.time.format.DateTimeFormatter) ZonedDateTime.now(java.time.ZonedDateTime.now) Package(org.molgenis.data.meta.model.Package) Transactional(org.springframework.transaction.annotation.Transactional) Attribute(org.molgenis.data.meta.model.Attribute) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) IOException(java.io.IOException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

Attribute (org.molgenis.data.meta.model.Attribute)3 AttributeFilterToFetchConverter.createDefaultAttributeFetch (org.molgenis.data.rest.v2.AttributeFilterToFetchConverter.createDefaultAttributeFetch)3 Instant (java.time.Instant)2 LocalDate (java.time.LocalDate)2 AggregateQuery (org.molgenis.data.aggregation.AggregateQuery)2 AggregateResult (org.molgenis.data.aggregation.AggregateResult)2 AttributeType (org.molgenis.data.meta.AttributeType)2 EntityType (org.molgenis.data.meta.model.EntityType)2 EntityPager (org.molgenis.data.rest.EntityPager)2 UnexpectedEnumException (org.molgenis.util.UnexpectedEnumException)2 Lists.transform (com.google.common.collect.Lists.transform)1 IOException (java.io.IOException)1 StringWriter (java.io.StringWriter)1 String.format (java.lang.String.format)1 ZonedDateTime.now (java.time.ZonedDateTime.now)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 MEDIUM (java.time.format.FormatStyle.MEDIUM)1 java.util (java.util)1 Objects.requireNonNull (java.util.Objects.requireNonNull)1 Collectors.toList (java.util.stream.Collectors.toList)1