Search in sources :

Example 66 with EntityType

use of org.molgenis.data.meta.model.EntityType in project molgenis by molgenis.

the class DefaultValueReferenceValidatorImpl method getDefaultValueMap.

private Multimap<String, Attribute> getDefaultValueMap(EntityType entityType) {
    Multimap<String, Attribute> defaultValueMultiMap = LinkedHashMultimap.create();
    dataService.query(ATTRIBUTE_META_DATA, Attribute.class).eq(REF_ENTITY_TYPE, entityType.getIdValue()).and().not().eq(DEFAULT_VALUE, null).findAll().forEach(attribute -> {
        if (EntityTypeUtils.isSingleReferenceType(attribute)) {
            Entity defaultEntityValue = (Entity) getDefaultTypedValue(attribute);
            defaultValueMultiMap.put(defaultEntityValue.getIdValue().toString(), attribute);
        } else if (EntityTypeUtils.isMultipleReferenceType(attribute)) {
            @SuppressWarnings("unchecked") Iterable<Entity> defaultEntitiesValue = (Iterable<Entity>) getDefaultTypedValue(attribute);
            defaultEntitiesValue.forEach(defaultEntityValue -> defaultValueMultiMap.put(defaultEntityValue.getIdValue().toString(), attribute));
        }
    });
    return defaultValueMultiMap;
}
Also used : Collection(java.util.Collection) Multimap(com.google.common.collect.Multimap) EntityTypeUtils(org.molgenis.data.support.EntityTypeUtils) Attribute(org.molgenis.data.meta.model.Attribute) EntityType(org.molgenis.data.meta.model.EntityType) Collectors(java.util.stream.Collectors) AttributeUtils.getDefaultTypedValue(org.molgenis.data.support.AttributeUtils.getDefaultTypedValue) Component(org.springframework.stereotype.Component) Stream(java.util.stream.Stream) Objects.requireNonNull(java.util.Objects.requireNonNull) DataService(org.molgenis.data.DataService) AttributeMetadata(org.molgenis.data.meta.model.AttributeMetadata) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) Entity(org.molgenis.data.Entity) Entity(org.molgenis.data.Entity) Attribute(org.molgenis.data.meta.model.Attribute)

Example 67 with EntityType

use of org.molgenis.data.meta.model.EntityType in project molgenis by molgenis.

the class RestControllerV2 method getEntityResponse.

private Map<String, Object> getEntityResponse(String entityTypeId, String untypedId, AttributeFilter attributeFilter, boolean includeCategories) {
    EntityType entityType = dataService.getEntityType(entityTypeId);
    Object id = getTypedValue(untypedId, entityType.getIdAttribute());
    Fetch fetch = AttributeFilterToFetchConverter.convert(attributeFilter, entityType, LanguageService.getCurrentUserLanguageCode());
    Entity entity = dataService.findOneById(entityTypeId, id, fetch);
    if (entity == null) {
        throw new UnknownEntityException(entityTypeId + " [" + untypedId + "] not found");
    }
    return createEntityResponse(entity, fetch, true, includeCategories);
}
Also used : EntityType(org.molgenis.data.meta.model.EntityType) AttributeFilterToFetchConverter.createDefaultAttributeFetch(org.molgenis.data.rest.v2.AttributeFilterToFetchConverter.createDefaultAttributeFetch)

Example 68 with EntityType

use of org.molgenis.data.meta.model.EntityType in project molgenis by molgenis.

the class RestControllerV2 method updateEntities.

/**
 * Try to update 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
 */
@PutMapping("/{entityTypeId}")
public synchronized void updateEntities(@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 {
        List<Entity> entities = request.getEntities().stream().map(e -> this.restService.toEntity(meta, e)).collect(toList());
        // update all entities
        this.dataService.update(entityTypeId, entities.stream());
        entities.forEach(entity -> restService.updateMappedByEntities(entity, dataService.findOneById(entityTypeId, entity.getIdValue())));
        response.setStatus(HttpServletResponse.SC_OK);
    } 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) 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)

Example 69 with EntityType

use of org.molgenis.data.meta.model.EntityType 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 70 with EntityType

use of org.molgenis.data.meta.model.EntityType in project molgenis by molgenis.

the class RestServiceTest method toEntityValueMrefToIntAttr.

@Test(dataProvider = "toEntityValueMrefProvider")
public void toEntityValueMrefToIntAttr(AttributeType attrType) {
    Entity entity0 = mock(Entity.class);
    Entity entity1 = mock(Entity.class);
    String refEntityName = "refEntity";
    Attribute refIdAttr = mock(Attribute.class);
    when(refIdAttr.getDataType()).thenReturn(INT);
    EntityType refEntityType = mock(EntityType.class);
    when(refEntityType.getId()).thenReturn(refEntityName);
    when(refEntityType.getIdAttribute()).thenReturn(refIdAttr);
    Attribute attr = mock(Attribute.class);
    when(attr.getDataType()).thenReturn(attrType);
    when(attr.getRefEntity()).thenReturn(refEntityType);
    when(entityManager.getReference(refEntityType, 0)).thenReturn(entity0);
    when(entityManager.getReference(refEntityType, 1)).thenReturn(entity1);
    // string
    Object entityValue = restService.toEntityValue(attr, "0,1", "test");
    assertEquals(entityValue, Arrays.asList(entity0, entity1));
}
Also used : EntityType(org.molgenis.data.meta.model.EntityType) Entity(org.molgenis.data.Entity) Attribute(org.molgenis.data.meta.model.Attribute) Test(org.testng.annotations.Test)

Aggregations

EntityType (org.molgenis.data.meta.model.EntityType)581 Test (org.testng.annotations.Test)367 Attribute (org.molgenis.data.meta.model.Attribute)315 Entity (org.molgenis.data.Entity)98 AbstractMockitoTest (org.molgenis.test.AbstractMockitoTest)71 DynamicEntity (org.molgenis.data.support.DynamicEntity)61 Stream (java.util.stream.Stream)44 EntityTypeIdentity (org.molgenis.data.security.EntityTypeIdentity)43 WithMockUser (org.springframework.security.test.context.support.WithMockUser)40 AbstractMolgenisSpringTest (org.molgenis.data.AbstractMolgenisSpringTest)36 QueryImpl (org.molgenis.data.support.QueryImpl)33 Package (org.molgenis.data.meta.model.Package)32 Objects.requireNonNull (java.util.Objects.requireNonNull)22 Collectors.toList (java.util.stream.Collectors.toList)22 BeforeMethod (org.testng.annotations.BeforeMethod)20 AttributeType (org.molgenis.data.meta.AttributeType)19 List (java.util.List)17 String.format (java.lang.String.format)16 ExplainedAttribute (org.molgenis.semanticsearch.explain.bean.ExplainedAttribute)16 Lists.newArrayList (com.google.common.collect.Lists.newArrayList)15