Search in sources :

Example 6 with WebMessageUtils.notFound

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound in project dhis2-core by dhis2.

the class DefaultCollectionService method delCollectionItems.

@Override
@SuppressWarnings("unchecked")
public void delCollectionItems(IdentifiableObject object, String propertyName, List<IdentifiableObject> objects) throws Exception {
    Schema schema = schemaService.getDynamicSchema(object.getClass());
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), object)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    if (!schema.haveProperty(propertyName)) {
        throw new WebMessageException(WebMessageUtils.notFound("Property " + propertyName + " does not exist on " + object.getClass().getName()));
    }
    Property property = schema.getProperty(propertyName);
    if (!property.isCollection() || !property.isIdentifiableObject()) {
        throw new WebMessageException(WebMessageUtils.conflict("Only identifiable object collections can be removed from."));
    }
    Collection<String> itemCodes = objects.stream().map(IdentifiableObject::getUid).collect(Collectors.toList());
    if (itemCodes.isEmpty()) {
        return;
    }
    List<? extends IdentifiableObject> items = manager.get(((Class<? extends IdentifiableObject>) property.getItemKlass()), itemCodes);
    manager.refresh(object);
    if (property.isOwner()) {
        Collection<IdentifiableObject> collection = (Collection<IdentifiableObject>) property.getGetterMethod().invoke(object);
        for (IdentifiableObject item : items) {
            if (collection.contains(item))
                collection.remove(item);
        }
    } else {
        Schema owningSchema = schemaService.getDynamicSchema(property.getItemKlass());
        Property owningProperty = owningSchema.propertyByRole(property.getOwningRole());
        for (IdentifiableObject item : items) {
            try {
                Collection<IdentifiableObject> collection = (Collection<IdentifiableObject>) owningProperty.getGetterMethod().invoke(item);
                if (collection.contains(object)) {
                    collection.remove(object);
                    manager.update(item);
                }
            } catch (Exception ex) {
            }
        }
    }
    manager.update(object);
    dbmsManager.clearSession();
    cacheManager.clearCache();
}
Also used : UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) Schema(org.hisp.dhis.schema.Schema) Collection(java.util.Collection) Property(org.hisp.dhis.schema.Property) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject)

Example 7 with WebMessageUtils.notFound

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound in project dhis2-core by dhis2.

the class UserRoleController method removeUserFromRole.

@RequestMapping(value = "/{id}/users/{userId}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeUserFromRole(@PathVariable(value = "id") String pvId, @PathVariable("userId") String pvUserId, HttpServletResponse response) throws WebMessageException {
    UserAuthorityGroup userAuthorityGroup = userService.getUserAuthorityGroup(pvId);
    if (userAuthorityGroup == null) {
        throw new WebMessageException(WebMessageUtils.notFound("UserRole does not exist: " + pvId));
    }
    User user = userService.getUser(pvUserId);
    if (user == null || user.getUserCredentials() == null) {
        throw new WebMessageException(WebMessageUtils.notFound("User does not exist: " + pvId));
    }
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), userAuthorityGroup)) {
        throw new DeleteAccessDeniedException("You don't have the proper permissions to delete this object.");
    }
    if (user.getUserCredentials().getUserAuthorityGroups().contains(userAuthorityGroup)) {
        user.getUserCredentials().getUserAuthorityGroups().remove(userAuthorityGroup);
        userService.updateUserCredentials(user.getUserCredentials());
    }
}
Also used : User(org.hisp.dhis.user.User) UserAuthorityGroup(org.hisp.dhis.user.UserAuthorityGroup) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DeleteAccessDeniedException(org.hisp.dhis.hibernate.exception.DeleteAccessDeniedException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with WebMessageUtils.notFound

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound in project dhis2-core by dhis2.

the class DataValueController method saveDataValue.

// ---------------------------------------------------------------------
// POST
// ---------------------------------------------------------------------
@PreAuthorize("hasRole('ALL') or hasRole('F_DATAVALUE_ADD')")
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void saveDataValue(@RequestParam String de, @RequestParam(required = false) String co, @RequestParam(required = false) String cc, @RequestParam(required = false) String cp, @RequestParam String pe, @RequestParam String ou, @RequestParam(required = false) String value, @RequestParam(required = false) String comment, @RequestParam(required = false) boolean followUp, HttpServletResponse response) throws WebMessageException {
    boolean strictPeriods = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_PERIODS);
    boolean strictCategoryOptionCombos = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_CATEGORY_OPTION_COMBOS);
    boolean strictOrgUnits = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_ORGANISATION_UNITS);
    boolean requireCategoryOptionCombo = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_REQUIRE_CATEGORY_OPTION_COMBO);
    // ---------------------------------------------------------------------
    // Input validation
    // ---------------------------------------------------------------------
    DataElement dataElement = getAndValidateDataElement(de);
    DataElementCategoryOptionCombo categoryOptionCombo = getAndValidateCategoryOptionCombo(co, requireCategoryOptionCombo);
    DataElementCategoryOptionCombo attributeOptionCombo = getAndValidateAttributeOptionCombo(cc, cp);
    Period period = getAndValidatePeriod(pe);
    OrganisationUnit organisationUnit = getAndValidateOrganisationUnit(ou);
    validateInvalidFuturePeriod(period, dataElement);
    validateAttributeOptionComboWithOrgUnitAndPeriod(attributeOptionCombo, organisationUnit, period);
    String valueValid = ValidationUtils.dataValueIsValid(value, dataElement);
    if (valueValid != null) {
        throw new WebMessageException(WebMessageUtils.conflict("Invalid value: " + value + ", must match data element type: " + dataElement.getValueType()));
    }
    String commentValid = ValidationUtils.commentIsValid(comment);
    if (commentValid != null) {
        throw new WebMessageException(WebMessageUtils.conflict("Invalid comment: " + comment));
    }
    OptionSet optionSet = dataElement.getOptionSet();
    if (!Strings.isNullOrEmpty(value) && optionSet != null && !optionSet.getOptionCodesAsSet().contains(value)) {
        throw new WebMessageException(WebMessageUtils.conflict("Data value is not a valid option of the data element option set: " + dataElement.getUid()));
    }
    if (strictPeriods && !dataElement.getPeriodTypes().contains(period.getPeriodType())) {
        throw new WebMessageException(WebMessageUtils.conflict("Period type of period: " + period.getIsoDate() + " not valid for data element: " + dataElement.getUid()));
    }
    if (strictCategoryOptionCombos && !dataElement.getCategoryOptionCombos().contains(categoryOptionCombo)) {
        throw new WebMessageException(WebMessageUtils.conflict("Category option combo: " + categoryOptionCombo.getUid() + " must be part of category combo of data element: " + dataElement.getUid()));
    }
    if (strictOrgUnits && !organisationUnit.hasDataElement(dataElement)) {
        throw new WebMessageException(WebMessageUtils.conflict("Data element: " + dataElement.getUid() + " must be assigned through data sets to organisation unit: " + organisationUnit.getUid()));
    }
    // ---------------------------------------------------------------------
    // Locking validation
    // ---------------------------------------------------------------------
    validateDataSetNotLocked(dataElement, period, organisationUnit, attributeOptionCombo);
    // ---------------------------------------------------------------------
    // Period validation
    // ---------------------------------------------------------------------
    validateDataInputPeriodForDataElementAndPeriod(dataElement, period);
    // ---------------------------------------------------------------------
    // Assemble and save data value
    // ---------------------------------------------------------------------
    String storedBy = currentUserService.getCurrentUsername();
    Date now = new Date();
    DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
    FileResource fileResource = null;
    if (dataValue == null) {
        if (dataElement.getValueType() == ValueType.FILE_RESOURCE) {
            if (value != null) {
                fileResource = fileResourceService.getFileResource(value);
                if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
                    throw new WebMessageException(WebMessageUtils.notFound(FileResource.class, value));
                }
                if (fileResource.isAssigned()) {
                    throw new WebMessageException(WebMessageUtils.conflict("File resource already assigned or linked to another data value"));
                }
                fileResource.setAssigned(true);
            } else {
                throw new WebMessageException(WebMessageUtils.conflict("Missing parameter 'value'"));
            }
        }
        dataValue = new DataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo, StringUtils.trimToNull(value), storedBy, now, StringUtils.trimToNull(comment));
        dataValueService.addDataValue(dataValue);
    } else {
        if (value == null && ValueType.TRUE_ONLY.equals(dataElement.getValueType())) {
            if (comment == null) {
                dataValueService.deleteDataValue(dataValue);
                return;
            } else {
                value = "false";
            }
        }
        if (dataElement.isFileType()) {
            fileResourceService.deleteFileResource(dataValue.getValue());
        }
        if (value != null) {
            dataValue.setValue(StringUtils.trimToNull(value));
        }
        if (comment != null) {
            dataValue.setComment(StringUtils.trimToNull(comment));
        }
        if (followUp) {
            dataValue.toggleFollowUp();
        }
        dataValue.setLastUpdated(now);
        dataValue.setStoredBy(storedBy);
        dataValueService.updateDataValue(dataValue);
    }
    if (fileResource != null) {
        fileResourceService.updateFileResource(fileResource);
    }
}
Also used : DataElement(org.hisp.dhis.dataelement.DataElement) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.datavalue.DataValue) FileResource(org.hisp.dhis.fileresource.FileResource) Period(org.hisp.dhis.period.Period) OptionSet(org.hisp.dhis.option.OptionSet) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) Date(java.util.Date) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with WebMessageUtils.notFound

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound in project dhis2-core by dhis2.

the class DashboardItemController method putDashboardItemShape.

@RequestMapping(value = "/{uid}/shape/{shape}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void putDashboardItemShape(@PathVariable String uid, @PathVariable DashboardItemShape shape, HttpServletRequest request, HttpServletResponse response) throws Exception {
    DashboardItem item = dashboardService.getDashboardItem(uid);
    if (item == null) {
        throw new WebMessageException(WebMessageUtils.notFound("Dashboard item does not exist: " + uid));
    }
    Dashboard dashboard = dashboardService.getDashboardFromDashboardItem(item);
    if (!aclService.canUpdate(currentUserService.getCurrentUser(), dashboard)) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this dashboard.");
    }
    item.setShape(shape);
    dashboardService.updateDashboardItem(item);
}
Also used : WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) Dashboard(org.hisp.dhis.dashboard.Dashboard) DashboardItem(org.hisp.dhis.dashboard.DashboardItem) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 10 with WebMessageUtils.notFound

use of org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound in project dhis2-core by dhis2.

the class ChartController method getChart.

//--------------------------------------------------------------------------
// Get data
//--------------------------------------------------------------------------
@RequestMapping(value = { "/{uid}/data", "/{uid}/data.png" }, method = RequestMethod.GET)
public void getChart(@PathVariable("uid") String uid, @RequestParam(value = "date", required = false) Date date, @RequestParam(value = "ou", required = false) String ou, @RequestParam(value = "width", defaultValue = "800", required = false) int width, @RequestParam(value = "height", defaultValue = "500", required = false) int height, @RequestParam(value = "attachment", required = false) boolean attachment, HttpServletResponse response) throws IOException, WebMessageException {
    Chart chart = chartService.getChartNoAcl(uid);
    if (chart == null) {
        throw new WebMessageException(WebMessageUtils.notFound("Chart does not exist: " + uid));
    }
    OrganisationUnit unit = ou != null ? organisationUnitService.getOrganisationUnit(ou) : null;
    JFreeChart jFreeChart = chartService.getJFreeChart(chart, date, unit, i18nManager.getI18nFormat());
    String filename = CodecUtils.filenameEncode(chart.getName()) + ".png";
    contextUtils.configureResponse(response, ContextUtils.CONTENT_TYPE_PNG, CacheStrategy.RESPECT_SYSTEM_SETTING, filename, attachment);
    ChartUtilities.writeChartAsPNG(response.getOutputStream(), jFreeChart, width, height);
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) JFreeChart(org.jfree.chart.JFreeChart) Chart(org.hisp.dhis.chart.Chart) JFreeChart(org.jfree.chart.JFreeChart) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)59 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)51 UpdateAccessDeniedException (org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException)17 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)17 User (org.hisp.dhis.user.User)12 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)11 InputStream (java.io.InputStream)7 BaseIdentifiableObject (org.hisp.dhis.common.BaseIdentifiableObject)7 IdentifiableObject (org.hisp.dhis.common.IdentifiableObject)7 Dashboard (org.hisp.dhis.dashboard.Dashboard)7 Property (org.hisp.dhis.schema.Property)7 MetadataImportParams (org.hisp.dhis.dxf2.metadata.MetadataImportParams)6 WebMessage (org.hisp.dhis.dxf2.webmessage.WebMessage)6 Schema (org.hisp.dhis.schema.Schema)6 DashboardItem (org.hisp.dhis.dashboard.DashboardItem)5 Event (org.hisp.dhis.dxf2.events.event.Event)5 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)5 WebOptions (org.hisp.dhis.webapi.webdomain.WebOptions)5 IOException (java.io.IOException)4 DataElement (org.hisp.dhis.dataelement.DataElement)4