Search in sources :

Example 6 with CampaignFormElement

use of de.symeda.sormas.api.campaign.form.CampaignFormElement in project SORMAS-Project by hzi-braunschweig.

the class CampaignFormMetaFacadeEjb method buildCampaignFormMetaFromJson.

@Override
public CampaignFormMetaDto buildCampaignFormMetaFromJson(String formId, String languageCode, String schemaDefinitionJson, String translationsJson) throws IOException {
    CampaignFormMetaDto campaignForm = new CampaignFormMetaDto();
    campaignForm.setFormId(formId);
    campaignForm.setLanguageCode(languageCode);
    ObjectMapper mapper = new ObjectMapper();
    if (StringUtils.isNotBlank(schemaDefinitionJson)) {
        campaignForm.setCampaignFormElements(Arrays.asList(mapper.readValue(schemaDefinitionJson, CampaignFormElement[].class)));
    }
    if (StringUtils.isNotBlank(translationsJson)) {
        campaignForm.setCampaignFormTranslations(Arrays.asList(mapper.readValue(translationsJson, CampaignFormTranslations[].class)));
    }
    return campaignForm;
}
Also used : CampaignFormTranslations(de.symeda.sormas.api.campaign.form.CampaignFormTranslations) CampaignFormMetaDto(de.symeda.sormas.api.campaign.form.CampaignFormMetaDto) CampaignFormElement(de.symeda.sormas.api.campaign.form.CampaignFormElement) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 7 with CampaignFormElement

use of de.symeda.sormas.api.campaign.form.CampaignFormElement in project SORMAS-Project by hzi-braunschweig.

the class CampaignFormMeta method getCampaignFormElementsList.

@Transient
public List<CampaignFormElement> getCampaignFormElementsList() {
    if (campaignFormElementsList == null) {
        if (StringUtils.isBlank(campaignFormElements)) {
            campaignFormElementsList = new ArrayList<>();
        } else {
            try {
                ObjectMapper mapper = new ObjectMapper();
                campaignFormElementsList = Arrays.asList(mapper.readValue(campaignFormElements, CampaignFormElement[].class));
            } catch (IOException e) {
                throw new ValidationRuntimeException("Content of campaignFormElements could not be parsed to List<CampaignFormElement> - ID: " + getId());
            }
        }
    }
    return campaignFormElementsList;
}
Also used : CampaignFormElement(de.symeda.sormas.api.campaign.form.CampaignFormElement) IOException(java.io.IOException) ValidationRuntimeException(de.symeda.sormas.api.utils.ValidationRuntimeException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Transient(javax.persistence.Transient)

Example 8 with CampaignFormElement

use of de.symeda.sormas.api.campaign.form.CampaignFormElement in project SORMAS-Project by hzi-braunschweig.

the class ExpressionProcessor method checkExpression.

private void checkExpression() {
    EvaluationContext context = refreshEvaluationContext(campaignFormBuilder.getFormValues());
    final List<CampaignFormElement> formElements = campaignFormBuilder.getFormElements();
    formElements.stream().filter(element -> element.getExpression() != null).forEach(e -> {
        try {
            final Expression expression = expressionParser.parseExpression(e.getExpression());
            final Class<?> valueType = expression.getValueType(context);
            final Object value = expression.getValue(context, valueType);
            campaignFormBuilder.setFieldValue(campaignFormBuilder.getFields().get(e.getId()), CampaignFormElementType.fromString(e.getType()), value);
        } catch (SpelEvaluationException evaluationException) {
            LOG.error("Error evaluating expression: {} / {}", evaluationException.getMessageCode(), evaluationException.getMessage());
        }
    });
}
Also used : SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) I18nProperties(de.symeda.sormas.api.i18n.I18nProperties) CampaignFormElement(de.symeda.sormas.api.campaign.form.CampaignFormElement) CampaignFormBuilder(de.symeda.sormas.ui.campaign.campaigndata.CampaignFormBuilder) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) HashSet(java.util.HashSet) Map(java.util.Map) MapAccessor(org.springframework.context.expression.MapAccessor) CampaignFormDataEntry(de.symeda.sormas.api.campaign.data.CampaignFormDataEntry) Property(com.vaadin.v7.data.Property) CampaignFormElementType(de.symeda.sormas.api.campaign.form.CampaignFormElementType) Logger(org.slf4j.Logger) ExpressionProcessorUtils.refreshEvaluationContext(de.symeda.sormas.api.campaign.ExpressionProcessorUtils.refreshEvaluationContext) Set(java.util.Set) Field(com.vaadin.v7.ui.Field) EvaluationContext(org.springframework.expression.EvaluationContext) ExpressionParser(org.springframework.expression.ExpressionParser) List(java.util.List) AbstractComponent(com.vaadin.ui.AbstractComponent) Expression(org.springframework.expression.Expression) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) Descriptions(de.symeda.sormas.api.i18n.Descriptions) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) Expression(org.springframework.expression.Expression) CampaignFormElement(de.symeda.sormas.api.campaign.form.CampaignFormElement) ExpressionProcessorUtils.refreshEvaluationContext(de.symeda.sormas.api.campaign.ExpressionProcessorUtils.refreshEvaluationContext) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext)

Example 9 with CampaignFormElement

use of de.symeda.sormas.api.campaign.form.CampaignFormElement in project SORMAS-Project by hzi-braunschweig.

the class CampaignFormDataImporter method insertImportRowIntoData.

private void insertImportRowIntoData(CampaignFormDataDto campaignFormData, String[] entry, String[] entryHeaderPath) throws InvalidColumnException, ImportErrorException {
    CampaignFormMetaDto campaignMetaDto = FacadeProvider.getCampaignFormMetaFacade().getCampaignFormMetaByUuid(campaignFormMetaUuid);
    campaignFormData.setCampaignFormMeta(new CampaignFormMetaReferenceDto(campaignFormMetaUuid, campaignMetaDto.getFormName()));
    List<String> formDataDtoFields = Stream.of(campaignFormData.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
    for (int i = 0; i < entry.length; i++) {
        final String propertyPath = entryHeaderPath[i];
        if (formDataDtoFields.contains(propertyPath)) {
            try {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyPath, campaignFormData.getClass());
                Class<?> propertyType = propertyDescriptor.getPropertyType();
                if (!executeDefaultInvoke(propertyDescriptor, campaignFormData, entry[i], new String[] { propertyPath })) {
                    final UserDto currentUserDto = userFacade.getByUuid(currentUser.getUuid());
                    final JurisdictionLevel jurisdictionLevel = UserRole.getJurisdictionLevel(currentUserDto.getUserRoles());
                    if (propertyType.isAssignableFrom(DistrictReferenceDto.class)) {
                        if (jurisdictionLevel == JurisdictionLevel.DISTRICT && !currentUserDto.getDistrict().getCaption().equals(entry[i])) {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryDistrictNotInUsersJurisdiction, entry[i], propertyPath));
                        }
                        List<DistrictReferenceDto> district = FacadeProvider.getDistrictFacade().getByName(entry[i], campaignFormData.getRegion(), true);
                        if (district.isEmpty()) {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryDoesNotExistDbOrRegion, entry[i], propertyPath));
                        } else if (district.size() > 1) {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importDistrictNotUnique, entry[i], propertyPath));
                        } else {
                            propertyDescriptor.getWriteMethod().invoke(campaignFormData, district.get(0));
                        }
                    } else if (propertyType.isAssignableFrom(CommunityReferenceDto.class)) {
                        if (jurisdictionLevel == JurisdictionLevel.COMMUNITY && !currentUserDto.getCommunity().getCaption().equals(entry[i])) {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryCommunityNotInUsersJurisdiction, entry[i], propertyPath));
                        }
                        List<CommunityReferenceDto> community = FacadeProvider.getCommunityFacade().getByName(entry[i], campaignFormData.getDistrict(), true);
                        if (community.isEmpty()) {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importEntryDoesNotExistDbOrDistrict, entry[i], propertyPath));
                        } else if (community.size() > 1) {
                            throw new ImportErrorException(I18nProperties.getValidationError(Validations.importCommunityNotUnique, entry[i], propertyPath));
                        } else {
                            propertyDescriptor.getWriteMethod().invoke(campaignFormData, community.get(0));
                        }
                    }
                }
            } catch (InvocationTargetException | IllegalAccessException e) {
                throw new ImportErrorException(I18nProperties.getValidationError(Validations.importErrorInColumn, propertyPath));
            } catch (IntrospectionException e) {
            // skip unknown fields
            } catch (ImportErrorException e) {
                throw e;
            } catch (Exception e) {
                LOGGER.error("Unexpected error when trying to import campaign form data: " + e.getMessage(), e);
                throw new ImportErrorException(I18nProperties.getValidationError(Validations.importUnexpectedError));
            }
        } else {
            CampaignFormDataEntry formEntry = new CampaignFormDataEntry(propertyPath, entry[i]);
            Optional<CampaignFormElement> existingFormElement = campaignMetaDto.getCampaignFormElements().stream().filter(e -> e.getId().equals(formEntry.getId())).findFirst();
            if (!existingFormElement.isPresent()) {
                // skip unknown fields
                continue;
            } else if (Objects.nonNull(formEntry.getValue()) && StringUtils.isNotBlank(formEntry.getValue().toString()) && !isEntryValid(existingFormElement.get(), formEntry)) {
                throw new ImportErrorException(I18nProperties.getValidationError(Validations.importWrongDataTypeError, entry[i], propertyPath));
            }
            if (formEntry.getValue() == null || StringUtils.isBlank(formEntry.getValue().toString())) {
                continue;
            }
            // Convert yes/no values to true/false
            if (CampaignFormElementType.YES_NO.toString().equals(existingFormElement.get().getType())) {
                String value = formEntry.getValue().toString();
                if ("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value)) {
                    formEntry.setValue(true);
                } else if ("no".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
                    formEntry.setValue(false);
                }
            }
            if (Objects.nonNull(campaignFormData.getFormValues())) {
                List<CampaignFormDataEntry> currentElementFormValues = campaignFormData.getFormValues();
                currentElementFormValues.add(formEntry);
                campaignFormData.setFormValues(currentElementFormValues);
            } else {
                List<CampaignFormDataEntry> formValues = new LinkedList<>();
                formValues.add(formEntry);
                campaignFormData.setFormValues(formValues);
            }
        }
    }
    ImportLineResultDto<CampaignFormDataDto> constraintErrors = validateConstraints(campaignFormData);
    if (constraintErrors.isError()) {
        throw new ImportErrorException(constraintErrors.getMessage());
    }
}
Also used : Arrays(java.util.Arrays) I18nProperties(de.symeda.sormas.api.i18n.I18nProperties) ValueSeparator(de.symeda.sormas.api.importexport.ValueSeparator) LoggerFactory(org.slf4j.LoggerFactory) UI(com.vaadin.ui.UI) Window(com.vaadin.ui.Window) StringUtils(org.apache.commons.lang3.StringUtils) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) ImportLineResult(de.symeda.sormas.ui.importer.ImportLineResult) UserRole(de.symeda.sormas.api.user.UserRole) CampaignFormElementType(de.symeda.sormas.api.campaign.form.CampaignFormElementType) CsvValidationException(com.opencsv.exceptions.CsvValidationException) CampaignFormDataSelectionField(de.symeda.sormas.ui.campaign.campaigndata.CampaignFormDataSelectionField) ImportLineResultDto(de.symeda.sormas.api.importexport.ImportLineResultDto) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) Collectors(java.util.stream.Collectors) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CommunityReferenceDto(de.symeda.sormas.api.infrastructure.community.CommunityReferenceDto) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) CampaignFormDataCriteria(de.symeda.sormas.api.campaign.data.CampaignFormDataCriteria) PropertyDescriptor(java.beans.PropertyDescriptor) Optional(java.util.Optional) CampaignFormMetaDto(de.symeda.sormas.api.campaign.form.CampaignFormMetaDto) JurisdictionLevel(de.symeda.sormas.api.user.JurisdictionLevel) RegionReferenceDto(de.symeda.sormas.api.infrastructure.region.RegionReferenceDto) ValidationRuntimeException(de.symeda.sormas.api.utils.ValidationRuntimeException) StreamResource(com.vaadin.server.StreamResource) VaadinUiUtil(de.symeda.sormas.ui.utils.VaadinUiUtil) FacadeProvider(de.symeda.sormas.api.FacadeProvider) CampaignFormElement(de.symeda.sormas.api.campaign.form.CampaignFormElement) CampaignFormDataDto(de.symeda.sormas.api.campaign.data.CampaignFormDataDto) LinkedList(java.util.LinkedList) CampaignFormDataEntry(de.symeda.sormas.api.campaign.data.CampaignFormDataEntry) Logger(org.slf4j.Logger) Validations(de.symeda.sormas.api.i18n.Validations) DistrictReferenceDto(de.symeda.sormas.api.infrastructure.district.DistrictReferenceDto) UserDto(de.symeda.sormas.api.user.UserDto) CampaignReferenceDto(de.symeda.sormas.api.campaign.CampaignReferenceDto) IOException(java.io.IOException) Field(java.lang.reflect.Field) Sizeable(com.vaadin.server.Sizeable) File(java.io.File) UserFacade(de.symeda.sormas.api.user.UserFacade) Consumer(java.util.function.Consumer) NumberUtils(org.apache.commons.lang3.math.NumberUtils) DataImporter(de.symeda.sormas.ui.importer.DataImporter) CampaignFormMetaReferenceDto(de.symeda.sormas.api.campaign.form.CampaignFormMetaReferenceDto) Strings(de.symeda.sormas.api.i18n.Strings) CampaignFormDataDto(de.symeda.sormas.api.campaign.data.CampaignFormDataDto) UserDto(de.symeda.sormas.api.user.UserDto) JurisdictionLevel(de.symeda.sormas.api.user.JurisdictionLevel) IntrospectionException(java.beans.IntrospectionException) CampaignFormElement(de.symeda.sormas.api.campaign.form.CampaignFormElement) CampaignFormMetaReferenceDto(de.symeda.sormas.api.campaign.form.CampaignFormMetaReferenceDto) CommunityReferenceDto(de.symeda.sormas.api.infrastructure.community.CommunityReferenceDto) List(java.util.List) LinkedList(java.util.LinkedList) PropertyDescriptor(java.beans.PropertyDescriptor) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) CampaignFormMetaDto(de.symeda.sormas.api.campaign.form.CampaignFormMetaDto) DistrictReferenceDto(de.symeda.sormas.api.infrastructure.district.DistrictReferenceDto) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvalidColumnException(de.symeda.sormas.api.importexport.InvalidColumnException) CsvValidationException(com.opencsv.exceptions.CsvValidationException) ImportErrorException(de.symeda.sormas.api.importexport.ImportErrorException) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ValidationRuntimeException(de.symeda.sormas.api.utils.ValidationRuntimeException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) CampaignFormDataEntry(de.symeda.sormas.api.campaign.data.CampaignFormDataEntry)

Example 10 with CampaignFormElement

use of de.symeda.sormas.api.campaign.form.CampaignFormElement in project SORMAS-Project by hzi-braunschweig.

the class CampaignFormBuilder method buildForm.

public void buildForm() {
    int currentCol = -1;
    GridLayout currentLayout = campaignFormLayout;
    int sectionCount = 0;
    for (CampaignFormElement formElement : formElements) {
        CampaignFormElementType type = CampaignFormElementType.fromString(formElement.getType());
        List<CampaignFormElementStyle> styles;
        if (formElement.getStyles() != null) {
            styles = Arrays.stream(formElement.getStyles()).map(CampaignFormElementStyle::fromString).collect(Collectors.toList());
        } else {
            styles = new ArrayList<>();
        }
        String dependingOnId = formElement.getDependingOn();
        Object[] dependingOnValues = formElement.getDependingOnValues();
        Object value = formValuesMap.get(formElement.getId());
        int occupiedColumns = getOccupiedColumns(type, styles);
        if (type == CampaignFormElementType.SECTION) {
            sectionCount++;
            GridLayout sectionLayout = new GridLayout(12, 1);
            sectionLayout.setMargin(new MarginInfo(true, true));
            CssStyles.style(sectionLayout, CssStyles.GRID_LAYOUT_SECTION, sectionCount % 2 == 0 ? CssStyles.GRID_LAYOUT_EVEN : CssStyles.GRID_LAYOUT_ODD);
            sectionLayout.setWidth(100, Unit.PERCENTAGE);
            currentLayout = sectionLayout;
            campaignFormLayout.addComponent(sectionLayout, 0, campaignFormLayout.getRows() - 1, 11, campaignFormLayout.getRows() - 1);
            campaignFormLayout.insertRow(campaignFormLayout.getRows());
        } else if (type == CampaignFormElementType.LABEL) {
            if ((currentCol + 1) + (occupiedColumns - 1) > 11 || currentCol > -1 && styles.contains(CampaignFormElementStyle.FIRST)) {
                currentLayout.insertRow(currentLayout.getRows());
                currentCol = -1;
            }
            Label field = new Label(get18nCaption(formElement.getId(), formElement.getCaption()));
            field.setId(formElement.getId());
            prepareComponent(field, formElement.getId(), formElement.getCaption(), type, styles);
            currentLayout.addComponent(field, (currentCol + 1), currentLayout.getRows() - 1, (currentCol + 1) + (occupiedColumns - 1), currentLayout.getRows() - 1);
            if (styles.contains(CampaignFormElementStyle.INLINE)) {
                currentCol += occupiedColumns;
            } else {
                currentLayout.insertRow(currentLayout.getRows());
                currentCol = -1;
            }
            if (dependingOnId != null && dependingOnValues != null) {
                setVisibilityDependency(field, dependingOnId, dependingOnValues);
            }
        } else {
            if ((currentCol + 1) + (occupiedColumns - 1) > 11 || currentCol > -1 && styles.contains(CampaignFormElementStyle.FIRST)) {
                currentLayout.insertRow(currentLayout.getRows());
                currentCol = -1;
            }
            Field<?> field = createField(formElement.getId(), formElement.getCaption(), type, styles);
            setFieldValue(field, type, value);
            field.setId(formElement.getId());
            field.setCaption(get18nCaption(formElement.getId(), formElement.getCaption()));
            field.setSizeFull();
            currentLayout.addComponent(field, (currentCol + 1), currentLayout.getRows() - 1, (currentCol + 1) + (occupiedColumns - 1), currentLayout.getRows() - 1);
            if (styles.contains(CampaignFormElementStyle.ROW)) {
                currentLayout.insertRow(currentLayout.getRows());
                currentCol = -1;
            } else {
                currentCol += occupiedColumns;
            }
            fields.put(formElement.getId(), field);
            if (dependingOnId != null && dependingOnValues != null) {
                setVisibilityDependency((AbstractComponent) field, dependingOnId, dependingOnValues);
            }
        }
    }
}
Also used : CampaignFormElement(de.symeda.sormas.api.campaign.form.CampaignFormElement) Label(com.vaadin.v7.ui.Label) Field(com.vaadin.v7.ui.Field) TextField(com.vaadin.v7.ui.TextField) AbstractComponent(com.vaadin.ui.AbstractComponent) GridLayout(com.vaadin.ui.GridLayout) MarginInfo(com.vaadin.shared.ui.MarginInfo) CampaignFormElementStyle(de.symeda.sormas.api.campaign.form.CampaignFormElementStyle) CampaignFormElementType(de.symeda.sormas.api.campaign.form.CampaignFormElementType)

Aggregations

CampaignFormElement (de.symeda.sormas.api.campaign.form.CampaignFormElement)10 CampaignFormDataEntry (de.symeda.sormas.api.campaign.data.CampaignFormDataEntry)6 CampaignFormElementType (de.symeda.sormas.api.campaign.form.CampaignFormElementType)6 HashMap (java.util.HashMap)4 View (android.view.View)3 ImageView (android.widget.ImageView)3 LinearLayout (android.widget.LinearLayout)3 TextView (android.widget.TextView)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 ValidationRuntimeException (de.symeda.sormas.api.utils.ValidationRuntimeException)3 CampaignFormMeta (de.symeda.sormas.app.backend.campaign.form.CampaignFormMeta)3 ControlPropertyField (de.symeda.sormas.app.component.controls.ControlPropertyField)3 AbstractComponent (com.vaadin.ui.AbstractComponent)2 GridLayout (com.vaadin.ui.GridLayout)2 Field (com.vaadin.v7.ui.Field)2 CampaignFormMetaDto (de.symeda.sormas.api.campaign.form.CampaignFormMetaDto)2 I18nProperties (de.symeda.sormas.api.i18n.I18nProperties)2 CampaignFormDataFragmentUtils.getOrCreateCampaignFormDataEntry (de.symeda.sormas.app.campaign.CampaignFormDataFragmentUtils.getOrCreateCampaignFormDataEntry)2 IOException (java.io.IOException)2 List (java.util.List)2