Search in sources :

Example 71 with Property

use of org.hisp.dhis.schema.Property in project dhis2-core by dhis2.

the class TestUtils method getFieldDescriptors.

public static Set<FieldDescriptor> getFieldDescriptors(Schema schema) {
    Set<FieldDescriptor> fieldDescriptors = new HashSet<>();
    Map<String, Property> persistedPropertyMap = schema.getPersistedProperties();
    for (String s : persistedPropertyMap.keySet()) {
        Property p = persistedPropertyMap.get(s);
        FieldDescriptor f = fieldWithPath(p.key()).description(TestUtils.getFieldDescription(p));
        if (!p.isRequired()) {
            f.optional().type(p.getPropertyType());
        }
        fieldDescriptors.add(f);
    }
    Map<String, Property> nonPersistedPropertyMap = schema.getNonPersistedProperties();
    for (String s : nonPersistedPropertyMap.keySet()) {
        Property p = nonPersistedPropertyMap.get(s);
        FieldDescriptor f = fieldWithPath(p.key()).description(TestUtils.getFieldDescription(p));
        if (!p.isRequired()) {
            f.optional().type(p.getPropertyType());
        }
        fieldDescriptors.add(f);
    }
    return fieldDescriptors;
}
Also used : Property(org.hisp.dhis.schema.Property) FieldDescriptor(org.springframework.restdocs.payload.FieldDescriptor) HashSet(java.util.HashSet)

Example 72 with Property

use of org.hisp.dhis.schema.Property in project dhis2-core by dhis2.

the class GeoJsonAttributesCheckTest method setUpTest.

@BeforeEach
public void setUpTest() {
    organisationUnit = new OrganisationUnit();
    organisationUnit.setName("A");
    attribute = new Attribute();
    attribute.setUid("geoJson");
    attribute.setName("geoJson");
    validationContext = Mockito.mock(ValidationContext.class);
    Schema schema = new Schema(OrganisationUnit.class, "organisationUnit", "organisationUnits");
    Property property = new Property();
    property.setPersisted(true);
    schema.getPropertyMap().put("attributeValues", property);
    SchemaService schemaService = Mockito.mock(SchemaService.class);
    when(schemaService.getDynamicSchema(OrganisationUnit.class)).thenReturn(schema);
    when(validationContext.getSchemaService()).thenReturn(schemaService);
    Preheat preheat = Mockito.mock(Preheat.class);
    when(preheat.getAttributeIdsByValueType(OrganisationUnit.class, ValueType.GEOJSON)).thenReturn(Sets.newSet("geoJson"));
    objectBundle = Mockito.mock(ObjectBundle.class);
    when(objectBundle.getPreheat()).thenReturn(preheat);
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) ObjectBundle(org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle) Attribute(org.hisp.dhis.attribute.Attribute) SchemaService(org.hisp.dhis.schema.SchemaService) Schema(org.hisp.dhis.schema.Schema) Preheat(org.hisp.dhis.preheat.Preheat) Property(org.hisp.dhis.schema.Property) ValidationContext(org.hisp.dhis.dxf2.metadata.objectbundle.validation.ValidationContext) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 73 with Property

use of org.hisp.dhis.schema.Property in project dhis2-core by dhis2.

the class DefaultLinkService method generateLink.

private <T> void generateLink(T object, String hrefBase, boolean deepScan) {
    Schema schema = schemaService.getDynamicSchema(HibernateProxyUtils.getRealClass(object));
    if (schema == null) {
        log.warn("Could not find schema for object of type " + object.getClass().getName() + ".");
        return;
    }
    generateHref(object, hrefBase);
    if (!deepScan) {
        return;
    }
    for (Property property : schema.getProperties()) {
        try {
            // TODO should we support non-idObjects?
            if (property.isIdentifiableObject()) {
                Object propertyObject = property.getGetterMethod().invoke(object);
                if (propertyObject == null) {
                    continue;
                }
                // unwrap hibernate PersistentCollection
                if (PersistentCollection.class.isAssignableFrom(propertyObject.getClass())) {
                    PersistentCollection collection = (PersistentCollection) propertyObject;
                    propertyObject = collection.getValue();
                }
                if (!property.isCollection()) {
                    generateHref(propertyObject, hrefBase);
                } else {
                    Collection<?> collection = (Collection<?>) propertyObject;
                    for (Object collectionObject : collection) {
                        generateHref(collectionObject, hrefBase);
                    }
                }
            }
        } catch (InvocationTargetException | IllegalAccessException ignored) {
        }
    }
}
Also used : PersistentCollection(org.hibernate.collection.spi.PersistentCollection) Schema(org.hisp.dhis.schema.Schema) Collection(java.util.Collection) PersistentCollection(org.hibernate.collection.spi.PersistentCollection) Property(org.hisp.dhis.schema.Property) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 74 with Property

use of org.hisp.dhis.schema.Property in project dhis2-core by dhis2.

the class AbstractCrudController method getCollectionItem.

//--------------------------------------------------------------------------
// Identifiable object collections add, delete
//--------------------------------------------------------------------------
@RequestMapping(value = "/{uid}/{property}/{itemId}", method = RequestMethod.GET)
@ResponseBody
public RootNode getCollectionItem(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @PathVariable("itemId") String pvItemId, @RequestParam Map<String, String> parameters, TranslateParams translateParams, HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = currentUserService.getCurrentUser();
    setUserContext(user, translateParams);
    if (!aclService.canRead(user, getEntityClass())) {
        throw new ReadAccessDeniedException("You don't have the proper permissions to read objects of this type.");
    }
    RootNode rootNode = getObjectInternal(pvUid, parameters, Lists.newArrayList(), Lists.newArrayList(pvProperty + "[:all]"), user);
    // TODO optimize this using field filter (collection filtering)
    if (!rootNode.getChildren().isEmpty() && rootNode.getChildren().get(0).isCollection()) {
        rootNode.getChildren().get(0).getChildren().stream().filter(Node::isComplex).forEach(node -> {
            node.getChildren().stream().filter(child -> child.isSimple() && child.getName().equals("id") && !((SimpleNode) child).getValue().equals(pvItemId)).forEach(child -> rootNode.getChildren().get(0).removeChild(node));
        });
    }
    if (rootNode.getChildren().isEmpty() || rootNode.getChildren().get(0).getChildren().isEmpty()) {
        throw new WebMessageException(WebMessageUtils.notFound(pvProperty + " with ID " + pvItemId + " could not be found."));
    }
    return rootNode;
}
Also used : ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) PathVariable(org.springframework.web.bind.annotation.PathVariable) Order(org.hisp.dhis.query.Order) RequestParam(org.springframework.web.bind.annotation.RequestParam) ErrorReport(org.hisp.dhis.feedback.ErrorReport) UserContext(org.hisp.dhis.common.UserContext) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) MergeService(org.hisp.dhis.schema.MergeService) RenderService(org.hisp.dhis.render.RenderService) InclusionStrategy(org.hisp.dhis.node.config.InclusionStrategy) UserSettingKey(org.hisp.dhis.user.UserSettingKey) Autowired(org.springframework.beans.factory.annotation.Autowired) WebMessageService(org.hisp.dhis.webapi.service.WebMessageService) NodeUtils(org.hisp.dhis.node.NodeUtils) UserSettingService(org.hisp.dhis.user.UserSettingService) Optional(com.google.common.base.Optional) MetadataImportService(org.hisp.dhis.dxf2.metadata.MetadataImportService) Locale(java.util.Locale) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Preset(org.hisp.dhis.node.Preset) PagerUtils(org.hisp.dhis.common.PagerUtils) Status(org.hisp.dhis.feedback.Status) Query(org.hisp.dhis.query.Query) ContextService(org.hisp.dhis.webapi.service.ContextService) DefaultRenderService(org.hisp.dhis.render.DefaultRenderService) LinkService(org.hisp.dhis.webapi.service.LinkService) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) MediaType(org.springframework.http.MediaType) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) SchemaService(org.hisp.dhis.schema.SchemaService) QueryService(org.hisp.dhis.query.QueryService) Property(org.hisp.dhis.schema.Property) Collectors(java.util.stream.Collectors) ImportReportMode(org.hisp.dhis.dxf2.metadata.feedback.ImportReportMode) MetadataExportService(org.hisp.dhis.dxf2.metadata.MetadataExportService) SimpleNode(org.hisp.dhis.node.types.SimpleNode) ObjectTranslation(org.hisp.dhis.translation.ObjectTranslation) List(java.util.List) ComplexNode(org.hisp.dhis.node.types.ComplexNode) Type(java.lang.reflect.Type) AclService(org.hisp.dhis.security.acl.AclService) Schema(org.hisp.dhis.schema.Schema) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RootNode(org.hisp.dhis.node.types.RootNode) Joiner(com.google.common.base.Joiner) HibernateCacheManager(org.hisp.dhis.cache.HibernateCacheManager) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) ImportReport(org.hisp.dhis.dxf2.metadata.feedback.ImportReport) CollectionNode(org.hisp.dhis.node.types.CollectionNode) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) CreateAccessDeniedException(org.hisp.dhis.hibernate.exception.CreateAccessDeniedException) HashMap(java.util.HashMap) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) Enums(com.google.common.base.Enums) TypeReport(org.hisp.dhis.feedback.TypeReport) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) Charset(java.nio.charset.Charset) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) WebMetadata(org.hisp.dhis.webapi.webdomain.WebMetadata) User(org.hisp.dhis.user.User) ErrorCode(org.hisp.dhis.feedback.ErrorCode) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) WebMessageUtils(org.hisp.dhis.dxf2.webmessage.WebMessageUtils) ObjectReport(org.hisp.dhis.feedback.ObjectReport) QueryParserException(org.hisp.dhis.query.QueryParserException) IdentifiableObjects(org.hisp.dhis.common.IdentifiableObjects) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) StreamUtils(org.springframework.util.StreamUtils) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) Node(org.hisp.dhis.node.Node) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) Pager(org.hisp.dhis.common.Pager) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) MetadataImportParams(org.hisp.dhis.dxf2.metadata.MetadataImportParams) CollectionService(org.hisp.dhis.dxf2.metadata.collection.CollectionService) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) HttpStatus(org.springframework.http.HttpStatus) OrderParams(org.hisp.dhis.dxf2.common.OrderParams) ParameterizedType(java.lang.reflect.ParameterizedType) CurrentUserService(org.hisp.dhis.user.CurrentUserService) TranslateParams(org.hisp.dhis.dxf2.common.TranslateParams) StringUtils(org.springframework.util.StringUtils) RootNode(org.hisp.dhis.node.types.RootNode) User(org.hisp.dhis.user.User) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) ReadAccessDeniedException(org.hisp.dhis.hibernate.exception.ReadAccessDeniedException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 75 with Property

use of org.hisp.dhis.schema.Property in project dhis2-core by dhis2.

the class AbstractCrudController method updateObjectProperty.

@RequestMapping(value = "/{uid}/{property}", method = { RequestMethod.PUT, RequestMethod.PATCH })
public void updateObjectProperty(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @RequestParam Map<String, String> rpParameters, HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebOptions options = new WebOptions(rpParameters);
    List<T> entities = getEntity(pvUid, options);
    if (entities.isEmpty()) {
        throw new WebMessageException(WebMessageUtils.notFound(getEntityClass(), pvUid));
    }
    if (!getSchema().haveProperty(pvProperty)) {
        throw new WebMessageException(WebMessageUtils.notFound("Property " + pvProperty + " does not exist on " + getEntityName()));
    }
    Property property = getSchema().getProperty(pvProperty);
    T persistedObject = entities.get(0);
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), persistedObject)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    if (!property.isWritable()) {
        throw new UpdateAccessDeniedException("This property is read-only.");
    }
    T object = deserialize(request);
    if (object == null) {
        throw new WebMessageException(WebMessageUtils.badRequest("Unknown payload format."));
    }
    Object value = property.getGetterMethod().invoke(object);
    property.getSetterMethod().invoke(persistedObject, value);
    manager.update(persistedObject);
    postPatchEntity(persistedObject);
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) WebOptions(org.hisp.dhis.webapi.webdomain.WebOptions) Property(org.hisp.dhis.schema.Property) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

Property (org.hisp.dhis.schema.Property)126 Schema (org.hisp.dhis.schema.Schema)69 IdentifiableObject (org.hisp.dhis.common.IdentifiableObject)36 ArrayList (java.util.ArrayList)32 HashMap (java.util.HashMap)26 Collection (java.util.Collection)21 BaseIdentifiableObject (org.hisp.dhis.common.BaseIdentifiableObject)21 List (java.util.List)20 Map (java.util.Map)16 Test (org.junit.jupiter.api.Test)16 Attribute (org.hisp.dhis.attribute.Attribute)14 ReflectionUtils (org.hisp.dhis.system.util.ReflectionUtils)14 Collectors (java.util.stream.Collectors)13 User (org.hisp.dhis.user.User)13 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)12 EmbeddedObject (org.hisp.dhis.common.EmbeddedObject)12 SimpleNode (org.hisp.dhis.node.types.SimpleNode)12 Query (org.hisp.dhis.query.Query)12 SchemaService (org.hisp.dhis.schema.SchemaService)12 Transactional (org.springframework.transaction.annotation.Transactional)12