Tony CHEMIT pushed to branch develop at ultreiaio / ird-observe Commits: f098afe6 by Tony CHEMIT at 2017-08-14T16:09:05+02:00 Review validation report (need translations in ES and EN) (See #806) - - - - - 17 changed files: - client/pom.xml - + client/src/main/ftl/validationReport_en.ftl - + client/src/main/ftl/validationReport_es.ftl - + client/src/main/ftl/validationReport_fr.ftl - client/src/main/java/fr/ird/observe/client/ObserveRunner.java - client/src/main/java/fr/ird/observe/client/ObserveTextGenerator.java - client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateEntityListCellRenderer.java - client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateModel.java - client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateUIHandler.java - + client/src/test/java/fr/ird/observe/client/ClientTestClassResource.java - + client/src/test/java/fr/ird/observe/client/ClientTestMethodResource.java - + client/src/test/java/fr/ird/observe/client/ClientTestSupport.java - + client/src/test/java/fr/ird/observe/client/DataSourcesForTestManager.java - + client/src/test/java/fr/ird/observe/client/ObserveTextGeneratorTest.java - client/src/test/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java → client/src/test/java/fr/ird/observe/client/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java - services/src/main/java/fr/ird/observe/services/service/actions/validate/ValidationResult.java - test/src/main/java/fr/ird/observe/test/TestClassResourceSupport.java Changes: ===================================== client/pom.xml ===================================== --- a/client/pom.xml +++ b/client/pom.xml @@ -348,6 +348,12 @@ <version>${project.version}</version> <scope>runtime</scope> </dependency> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>test</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> <!-- jaxx dependencies --> @@ -709,6 +715,7 @@ <template>dataSourceSelectModeResume</template> <template>initStorage</template> <template>storageModelDataSourceConfiguration</template> + <template>validationResult</template> </templateList> </configuration> </execution> ===================================== client/src/main/ftl/validationReport_en.ftl ===================================== --- /dev/null +++ b/client/src/main/ftl/validationReport_en.ftl @@ -0,0 +1,40 @@ +<html> +<body> +<b>#TODO</b> +<h1>Rapport de validation</h1> + +<h2>Configuration</h2> + +<ul> + <li>Rapport de validation généré le ${now}</li> + <li>Scopes : ${scopes?join(", ")}</li> + <li>Context : ${contextName}</li> +</ul> + +<#list messageTypes as type> +<h2>${decorateType(type)}</h2> +<table> + <thead> + <tr> + <th>Identifiant</th> + <th>Libellé</th> + <th>Scope</th> + <th>Champs</th> + <th>Message</th> + </tr> + </thead> + <#list validationResult.getDtosForType(type) as dto> + <#list validationResult.getMessagesForId(dto.id) as message> + <tr> + <td>${dto.id}</td> + <td>${decorateReference(dto.reference)}</td> + <td>${message.scope}</td> + <td>${decorateProperty(message.fieldName)}</td> + <td>${message.message}</td> + </tr> + </#list> + </#list> +</table> +</#list> +</body> +</html> ===================================== client/src/main/ftl/validationReport_es.ftl ===================================== --- /dev/null +++ b/client/src/main/ftl/validationReport_es.ftl @@ -0,0 +1,40 @@ +<html> +<body> +<b>#TODO</b> +<h1>Rapport de validation</h1> + +<h2>Configuration</h2> + +<ul> + <li>Rapport de validation généré le ${now}</li> + <li>Scopes : ${scopes?join(", ")}</li> + <li>Context : ${contextName}</li> +</ul> + +<#list messageTypes as type> +<h2>${decorateType(type)}</h2> +<table> + <thead> + <tr> + <th>Identifiant</th> + <th>Libellé</th> + <th>Scope</th> + <th>Champs</th> + <th>Message</th> + </tr> + </thead> + <#list validationResult.getDtosForType(type) as dto> + <#list validationResult.getMessagesForId(dto.id) as message> + <tr> + <td>${dto.id}</td> + <td>${decorateReference(dto.reference)}</td> + <td>${message.scope}</td> + <td>${decorateProperty(message.fieldName)}</td> + <td>${message.message}</td> + </tr> + </#list> + </#list> +</table> +</#list> +</body> +</html> ===================================== client/src/main/ftl/validationReport_fr.ftl ===================================== --- /dev/null +++ b/client/src/main/ftl/validationReport_fr.ftl @@ -0,0 +1,40 @@ +<html> +<body> + +<h1>Rapport de validation</h1> + +<h2>Configuration</h2> + +<ul> + <li>Rapport de validation généré le ${now}</li> + <li>Scopes : ${scopes?join(", ")}</li> + <li>Context : ${contextName}</li> +</ul> + +<#list messageTypes as type> +<h2>${decorateType(type)}</h2> +<table> + <thead> + <tr> + <th>Identifiant</th> + <th>Libellé</th> + <th>Scope</th> + <th>Champs</th> + <th>Message</th> + </tr> + </thead> + <#list validationResult.getDtosForType(type) as dto> + <#list validationResult.getMessagesForId(dto.id) as message> + <tr> + <td>${dto.id}</td> + <td>${decorateReference(dto.reference)}</td> + <td>${message.scope}</td> + <td>${decorateProperty(message.fieldName)}</td> + <td>${message.message}</td> + </tr> + </#list> + </#list> +</table> +</#list> +</body> +</html> ===================================== client/src/main/java/fr/ird/observe/client/ObserveRunner.java ===================================== --- a/client/src/main/java/fr/ird/observe/client/ObserveRunner.java +++ b/client/src/main/java/fr/ird/observe/client/ObserveRunner.java @@ -87,6 +87,10 @@ public abstract class ObserveRunner extends ApplicationRunner { private static ObserveResourceManager resourceManager; + public static void setResourceManager(ObserveResourceManager resourceManager) { + ObserveRunner.resourceManager = resourceManager; + } + private static ObserveActionExecutor actionExecutor; public static ObserveRunner getRunner() { @@ -481,7 +485,7 @@ public abstract class ObserveRunner extends ApplicationRunner { } } - private void initI18n(ClientConfig config) { + public static void initI18n(ClientConfig config) { I18n.close(); ===================================== client/src/main/java/fr/ird/observe/client/ObserveTextGenerator.java ===================================== --- a/client/src/main/java/fr/ird/observe/client/ObserveTextGenerator.java +++ b/client/src/main/java/fr/ird/observe/client/ObserveTextGenerator.java @@ -25,9 +25,11 @@ package fr.ird.observe.client; import fr.ird.observe.client.configuration.ClientConfig; import fr.ird.observe.client.db.ObserveDataSourcesManager; import fr.ird.observe.client.db.ObserveSwingDataSource; +import fr.ird.observe.client.ui.admin.validate.ValidateModel; import fr.ird.observe.client.ui.storage.StorageUIModel; import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.services.service.actions.validate.ValidationResult; import freemarker.cache.FileTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; @@ -64,6 +66,8 @@ public class ObserveTextGenerator { private static final String INIT_STORAGE_TEMPLATE = "initStorage.ftl"; + private static final String VALIDATION_REPORT_TEMPLATE = "validationReport.ftl"; + private final Configuration freemarkerConfiguration; private final ClientConfig observeConfiguration; @@ -115,6 +119,10 @@ public class ObserveTextGenerator { return generateHtml(INIT_STORAGE_TEMPLATE, model); } + public String getValidationReport(ValidateModel model) { + return generateHtml(VALIDATION_REPORT_TEMPLATE, model); + } + protected String generateHtml(String templateName, Object model) { return generateHtml(observeConfiguration.getLocale(), templateName, model); } ===================================== client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateEntityListCellRenderer.java ===================================== --- a/client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateEntityListCellRenderer.java +++ b/client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateEntityListCellRenderer.java @@ -21,12 +21,12 @@ */ package fr.ird.observe.client.ui.admin.validate; -import com.google.common.collect.ImmutableSet; import fr.ird.observe.client.ObserveSwingApplicationContext; import fr.ird.observe.services.decoration.DecoratorService; import fr.ird.observe.services.decoration.ObserveI18nDecoratorHelper; import fr.ird.observe.services.dto.reference.AbstractReference; import fr.ird.observe.services.dto.reference.ReferentialReference; +import fr.ird.observe.services.service.actions.validate.ValidationResult; import java.awt.Component; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; @@ -61,15 +61,15 @@ public class ValidateEntityListCellRenderer extends DefaultListCellRenderer impl this.model = model; renderCache = new HashMap<>(); // on écoute les modifications de messages sur le model - this.model.addPropertyChangeListener(ValidateModel.PROPERTY_MESSAGES, this); + this.model.addPropertyChangeListener(ValidateModel.PROPERTY_VALIDATION_RESULT, this); } @Override public void propertyChange(PropertyChangeEvent evt) { - ImmutableSet value = (ImmutableSet) evt.getNewValue(); + ValidationResult value = (ValidationResult) evt.getNewValue(); if (log.isDebugEnabled()) { - log.debug(String.format("messages changed : %d, rebuild render cache", value == null ? 0 : value.size())); + log.debug(String.format("messages changed : %d, rebuild render cache", value == null ? 0 : value.getData().size())); } synchronized (renderCache) { renderCache.clear(); ===================================== client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateModel.java ===================================== --- a/client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateModel.java +++ b/client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateModel.java @@ -30,29 +30,36 @@ import fr.ird.observe.client.ui.admin.AdminActionModel; import fr.ird.observe.client.ui.admin.AdminStep; import fr.ird.observe.client.ui.admin.AdminUIModel; import fr.ird.observe.client.ui.util.ProgressModel; +import fr.ird.observe.services.decoration.DecoratorService; +import fr.ird.observe.services.decoration.ObserveI18nDecoratorHelper; import fr.ird.observe.services.dto.reference.AbstractReference; +import fr.ird.observe.services.dto.reference.DataReference; import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.service.actions.validate.ValidateService; +import fr.ird.observe.services.service.actions.validate.ValidationResult; import fr.ird.observe.services.service.actions.validate.ValidationResultDto; import fr.ird.observe.services.service.actions.validate.ValidationResultDtoMessage; -import fr.ird.observe.services.service.actions.validate.ValidateService; import fr.ird.observe.services.validation.ValidatorDto; +import java.beans.Introspector; import java.beans.PropertyChangeListener; import java.io.File; -import java.util.Comparator; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.EnumMap; import java.util.EnumSet; import java.util.LinkedHashSet; -import java.util.List; import java.util.Set; -import java.util.TreeSet; import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableInt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.jaxx.runtime.swing.wizard.ext.WizardState; import org.nuiton.validator.NuitonValidatorScope; + +import static org.nuiton.i18n.I18n.t; + /** * Modele pour preparer une validation de donnees d'une base. * @@ -66,7 +73,8 @@ public class ValidateModel extends AdminActionModel { static final String PROPERTY_MODEL_MODE = "modelMode"; private static final String PROPERTY_GENERATE_REPORT = "generateReport"; private static final String PROPERTY_REPORT_FILE = "reportFile"; - static final String PROPERTY_MESSAGES = "messages"; + + static final String PROPERTY_VALIDATION_RESULT = "validationResult"; /** le pattern du fichier de rapport après validation */ private static final String REPORT_PATTERN = "report-%1$tF--%1$tk-%1$tM-%1$tS.txt"; @@ -95,18 +103,16 @@ public class ValidateModel extends AdminActionModel { /** les validateurs selectionnées */ private Set<ValidatorDto> validators; - /** le dictionnaire des paths d'entites detectees */ - private final Set<ValidationResultDto> messages; - private final Set<Class> messagesTypes; - private final ProgressModel progressModel = new ProgressModel(); + private ValidationResult<?> validationResult; + private DecoratorService decoratorService; + public ValidateModel() { super(AdminStep.VALIDATE); scopes = EnumSet.noneOf(NuitonValidatorScope.class); this.messagesTypes = new LinkedHashSet<>(); - this.messages = new TreeSet<>(Comparator.comparing(m -> m.getReference().getId())); } @@ -184,36 +190,41 @@ public class ValidateModel extends AdminActionModel { return validators; } - public void setMessages(ImmutableSet<ValidationResultDto> messages) { - this.messages.clear(); + @SuppressWarnings("unused") + public ValidationResult<?> getValidationResult() { + return validationResult; + } + + public void setValidationResult(ValidationResult<?> validationResult) { + this.validationResult = validationResult; this.messagesTypes.clear(); - this.messages.addAll(messages); - Set<Class> collect = messages.stream().map(m -> m.getReference().getType()).collect(Collectors.toSet()); - this.messagesTypes.addAll(collect); - firePropertyChange(PROPERTY_MESSAGES, messages); + if (validationResult != null) { + this.messagesTypes.addAll(validationResult.getTypes()); + } + firePropertyChange(PROPERTY_VALIDATION_RESULT, null, validationResult); } - Set<Class> getMessageTypes() { + public Set<Class> getMessageTypes() { return messagesTypes; } - List<AbstractReference> getMessagesDto(Class dtoType) { + public ImmutableSet<ValidationResultDto> getMessagesDto(Class dtoType) { - return messages.stream().filter(m -> dtoType.equals(m.getReference().getType())).map(ValidationResultDto::getReference).collect(Collectors.toList()); + return validationResult == null ? ImmutableSet.of() : validationResult.getDtosForType(dtoType); } - public Set<ValidationResultDto> getMessages() { - return messages; + public ImmutableSet<ValidationResultDto> getMessages() { + return validationResult == null ? ImmutableSet.of() : validationResult.getData(); } - List<ValidationResultDtoMessage> getMessages(AbstractReference<?> dtoType) { + public ImmutableSet<ValidationResultDtoMessage> getMessages(AbstractReference<?> dtoType) { - return messages.stream().filter(m -> dtoType.equals(m.getReference())).flatMap(m -> m.getMessages().stream()).collect(Collectors.toList()); + return validationResult == null ? ImmutableSet.of() : validationResult.getMessagesForId(dtoType.getId()); } - void addScope(NuitonValidatorScope scope) { + public void addScope(NuitonValidatorScope scope) { scopes.add(scope); validators = null; firePropertyChange(PROPERTY_SCOPES, null, scopes); @@ -228,9 +239,6 @@ public class ValidateModel extends AdminActionModel { @Override public void destroy() { super.destroy(); - if (messages != null) { - setMessages(ImmutableSet.of()); - } if (validators != null) { validators = null; } @@ -270,6 +278,12 @@ public class ValidateModel extends AdminActionModel { setReportFile(reportFile); } + private static final SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyy HH:mm"); + + public String getNow() { + return df.format(new Date()); + } + public boolean validate(AdminUIModel uiModel) { return uiModel.validate(AdminStep.SELECT_DATA) && uiModel.getStepState(step) == WizardState.SUCCESSED; } @@ -294,8 +308,8 @@ public class ValidateModel extends AdminActionModel { } - boolean withoutMessages() { - return messages.isEmpty(); + public boolean withoutMessages() { + return validationResult == null || validationResult.getData().isEmpty(); } EnumMap<NuitonValidatorScope, Integer> getScopesCount(AbstractReference<?> value) { @@ -305,10 +319,14 @@ public class ValidateModel extends AdminActionModel { temp.put(scope, new MutableInt()); } - messages.stream() - .filter(m -> value.equals(m.getReference())).flatMap(m -> m.getMessages().stream()) - .map(ValidationResultDtoMessage::getScope) - .forEach(s -> temp.get(s).incrementAndGet()); + if (validationResult != null) { + getMessages().stream() + .filter(m -> value.equals(m.getReference())).flatMap(m -> m.getMessages().stream()) + .map(ValidationResultDtoMessage::getScope) + .forEach(s -> temp.get(s).incrementAndGet()); + + } + EnumMap<NuitonValidatorScope, Integer> result = new EnumMap<>(NuitonValidatorScope.class); temp.entrySet().stream() @@ -316,4 +334,24 @@ public class ValidateModel extends AdminActionModel { .forEach(entry -> result.put(entry.getKey(), entry.getValue().toInteger())); return result; } + + @SuppressWarnings({"unchecked", "unused"}) + public String decorateReference(AbstractReference reference) { + if (reference instanceof DataReference<?>) { + return decoratorService.getDataReferenceDecorator(reference.getType()).toString(reference); + } + return decoratorService.getReferentialReferenceDecorator(reference.getType()).toString(reference); + } + + public String decorateType(Class type) { + return t(ObserveI18nDecoratorHelper.getTypeI18nKey(type)); + } + + public String decorateProperty(String propertyName) { + return t(ObserveI18nDecoratorHelper.getPropertyI18nKey(propertyName)); + } + + public void setDecoratorService(DecoratorService decoratorService) { + this.decoratorService = decoratorService; + } } ===================================== client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateUIHandler.java ===================================== --- a/client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateUIHandler.java +++ b/client/src/main/java/fr/ird/observe/client/ui/admin/validate/ValidateUIHandler.java @@ -37,16 +37,16 @@ import fr.ird.observe.client.ui.admin.config.SelectDataUI; import fr.ird.observe.client.ui.tree.selection.SelectionTreeModel; import fr.ird.observe.client.ui.util.ObserveValidationMessageTableRenderer; import fr.ird.observe.client.ui.util.ProgressModel; -import fr.ird.observe.services.decoration.DecoratorService; import fr.ird.observe.services.decoration.ObserveI18nDecoratorHelper; +import fr.ird.observe.services.dto.constants.ReferentialLocale; import fr.ird.observe.services.dto.reference.AbstractReference; import fr.ird.observe.services.dto.reference.DataReference; import fr.ird.observe.services.service.actions.validate.DataValidationRequest; import fr.ird.observe.services.service.actions.validate.ReferentialValidationRequest; -import fr.ird.observe.services.service.actions.validate.ValidationResultDtoMessage; -import fr.ird.observe.services.service.actions.validate.ValidationResultDto; import fr.ird.observe.services.service.actions.validate.ValidateService; import fr.ird.observe.services.service.actions.validate.ValidationResult; +import fr.ird.observe.services.service.actions.validate.ValidationResultDto; +import fr.ird.observe.services.service.actions.validate.ValidationResultDtoMessage; import fr.ird.observe.services.validation.ValidatorDto; import java.io.File; import java.io.IOException; @@ -54,6 +54,7 @@ import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import javax.swing.DefaultListModel; import javax.swing.JCheckBox; import javax.swing.JTable; @@ -229,12 +230,12 @@ public class ValidateUIHandler extends AdminTabUIHandler<ValidateUI> implements Class<?> type = (Class<?>) o; - List<AbstractReference> refs = tabUI.getStepModel().getMessagesDto(type); - for (AbstractReference<?> ref : Iterables.limit(refs, 100)) { + ImmutableSet<ValidationResultDto> refs = tabUI.getStepModel().getMessagesDto(type); + for (ValidationResultDto ref : Iterables.limit(refs, 100)) { if (log.isDebugEnabled()) { log.debug("add ref = " + ref); } - tabUI.refModel.addElement(ref); + tabUI.refModel.addElement(ref.getReference()); } tabUI.refList.setSelectedIndex(0); } finally { @@ -268,7 +269,7 @@ public class ValidateUIHandler extends AdminTabUIHandler<ValidateUI> implements log.debug(ref); } - List<ValidationResultDtoMessage> messages = tabUI.getStepModel().getMessages(ref); + ImmutableSet<ValidationResultDtoMessage> messages = tabUI.getStepModel().getMessages(ref); tabUI.messagesModel.setMessages(messages); @@ -349,7 +350,7 @@ public class ValidateUIHandler extends AdminTabUIHandler<ValidateUI> implements AdminUIModel model = ui.getModel(); // on vide les anciens messages ValidateModel stepModel = model.getValidateModel(); - stepModel.setMessages(ImmutableSet.of()); + stepModel.setValidationResult(null); SelectionTreeModel dataModel = model.getSelectDataModel().getSelectionDataModel(); @@ -380,6 +381,8 @@ public class ValidateUIHandler extends AdminTabUIHandler<ValidateUI> implements ImmutableSet<NuitonValidatorScope> scopes = ImmutableSet.copyOf(stepModel.getScopes()); String contextName = stepModel.getContextName(); + ValidationResult<?> result = null; + if (dataModel.isLoadReferential()) { // validation des referentiels selectionnes @@ -391,11 +394,17 @@ public class ValidateUIHandler extends AdminTabUIHandler<ValidateUI> implements progressModel.incrementsCurrentStep(); - ValidationResult<ReferentialValidationRequest> result = validateService.validateReferential(request); + result = validateService.validateReferential(request); - messages.addAll(result.getData()); } else if (dataModel.isUseData()) { + DataValidationRequest mainRequest = new DataValidationRequest(); + mainRequest.setDataIds(ImmutableSet.copyOf(dataModel.getSelectedData().stream().map(DataReference::getId).collect(Collectors.toSet()))); + mainRequest.setScopes(scopes); + mainRequest.setValidationContext(contextName); + + ValidationResult.Builder<DataValidationRequest> resultBuilder = ValidationResult.builder(ReferentialLocale.valueOf(ObserveSwingApplicationContext.get().getConfig().getDbLocale()), mainRequest); + for (DataReference<?> dataReference : dataModel.getSelectedData()) { String id = dataReference.getId(); @@ -407,17 +416,20 @@ public class ValidateUIHandler extends AdminTabUIHandler<ValidateUI> implements sendMessage(t("observe.actions.validate.message.validate.trip", getDecoratorService().getDataReferenceDecorator(dataReference.getType()).toString(dataReference))); progressModel.incrementsCurrentStep(); - ValidationResult<DataValidationRequest> result = validateService.validateData(request); - messages.addAll(result.getData()); + + result = validateService.validateData(request); + resultBuilder.addMessages(result.getData()); } + result = resultBuilder.build(); + } else throw new IllegalStateException(); progressModel.incrementsCurrentStep(); dataSourceToValidate.close(); - stepModel.setMessages(messages.build()); + stepModel.setValidationResult(result); } @@ -445,60 +457,18 @@ public class ValidateUIHandler extends AdminTabUIHandler<ValidateUI> implements } } - //FIXME A remplacer par une template private void generateReportFile(ValidateModel validationModel) throws IOException { File reportFile = validationModel.getReportFile(); if (log.isInfoEnabled()) { log.info("save report in " + reportFile); } - DecoratorService service = getDecoratorService(); - StringBuilder builder = new StringBuilder(); - builder.append(LINE).append('\n'); + validationModel.setDecoratorService(getDecoratorService()); - builder.append(t("observe.actions.validate.report.title", new Date())).append('\n'); - builder.append(t("observe.actions.validate.report.scopes", validationModel.getScopes())).append('\n'); - builder.append(t("observe.actions.validate.report.contextName", validationModel.getContextName())).append('\n'); + String content = ObserveSwingApplicationContext.get().getTextGenerator().getValidationReport(validationModel); -// Map<Class<? extends IdDto>, ValidateResultForDtoType<? extends IdDto>> messages = validationModel.getMessages(); -// -// builder.append(t("observe.actions.validate.report.entities.with.messages", messages.size())).append('\n'); -// builder.append(LINE).append('\n').append('\n'); -// -// for (ValidateResultForDtoType<?> validateResultForDtoType : messages.values()) { -// -// ImmutableSet<? extends ValidateResultForDto<?>> validateResultForHelper = validateResultForDtoType.getValidateResultForDto(); -// for (ValidateResultForDto<?> validateResultForDto : validateResultForHelper) { -// AbstractReference<?> referenceDto = validateResultForDto.getReference(); -// -// String refStr = service.getReferenceDecorator(referenceDto.getType()).toString(referenceDto); -// -// Set<ValidationResultDtoMessage> refMessages = validateResultForDto.getMessages(); -// -// EnumSet<NuitonValidatorScope> scopes = getScopes(validateResultForDto); -// -// builder.append(t("observe.actions.validate.report.entity", referenceDto.getId(), refStr, refMessages.size(), scopes)).append('\n'); -// for (NuitonValidatorScope scope : scopes) { -// -// List<ValidationResultDtoMessage> messagesByScope = scopeMessageFilter(scope, validateResultForDto); -// -// for (ValidationResultDtoMessage message : messagesByScope) { -// -// builder.append(message.getScope()).append(" - ").append(message.getMessage()).append('\n'); -// -// } -// -// builder.append('\n'); -// } -// -// } -// builder.append(LINE).append('\n').append('\n'); -// } - - String content = builder.toString(); - if (log.isInfoEnabled()) { - log.info(content); - } + log.debug(content); + addMessage(AdminStep.SHOW_RESUME, content); FileUtils.write(reportFile, content, Charsets.UTF_8.name()); } ===================================== client/src/test/java/fr/ird/observe/client/ClientTestClassResource.java ===================================== --- /dev/null +++ b/client/src/test/java/fr/ird/observe/client/ClientTestClassResource.java @@ -0,0 +1,172 @@ +package fr.ird.observe.client; + +/* + * #%L + * ObServe :: Services ToPIA Implementation + * %% + * Copyright (C) 2008 - 2017 IRD, Code Lutin, Ultreia.io + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.client.configuration.ClientConfig; +import fr.ird.observe.client.db.ObserveSwingDataSource; +import fr.ird.observe.services.configuration.topia.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.dto.source.DataSourceCreateConfigurationDto; +import fr.ird.observe.services.dto.source.DataSourceCreateWithNoReferentialImportException; +import fr.ird.observe.services.dto.source.IncompatibleDataSourceCreateConfigurationException; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.test.ObserveTestConfiguration; +import fr.ird.observe.test.ObserveTestResources; +import fr.ird.observe.test.TestClassResourceSupport; +import fr.ird.observe.test.spi.DatabaseClassifier; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Locale; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.runner.Description; +import org.nuiton.i18n.I18n; +import org.nuiton.i18n.init.ClassPathI18nInitializer; +import org.nuiton.version.Version; + +/** + * Created on 18/08/15. + * + * @author Tony Chemit - dev@tchemit.fr + */ +public class ClientTestClassResource extends TestClassResourceSupport { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ClientTestClassResource.class); + + private final DataSourcesForTestManager dataSourcesForTestManager; + private ObserveSwingApplicationContext applicationContext; + + public ClientTestClassResource() { + this(DatabaseClassifier.DEFAULT); + } + + public ClientTestClassResource(DatabaseClassifier classifier) { + super(classifier); + + dataSourcesForTestManager = new DataSourcesForTestManager(); + } + + public DataSourcesForTestManager getDataSourcesForTestManager() { + return dataSourcesForTestManager; + } + + public ObserveSwingApplicationContext getApplicationContext() { + return applicationContext; + } + + public ObserveSwingDataSource createDataSourceConfiguration(Version dbVersion, String dbName, File targetPath, String login, char[] password) throws DataSourceCreateWithNoReferentialImportException, IOException, IncompatibleDataSourceCreateConfigurationException, DatabaseNotFoundException, DatabaseConnexionNotAuthorizedException, BabModelVersionException { + + ObserveDataSourceConfigurationTopiaH2 sharedDatabaseConfiguration = dataSourcesForTestManager.createSharedDataSourceConfigurationH2(dbVersion, dbName, login, password); + + File sharedDatabaseFile = sharedDatabaseConfiguration.getDatabaseFile(); + + ObserveDataSourceConfigurationTopiaH2 dataSourceConfiguration; + + ObserveSwingDataSource observeSwingDataSource; + boolean sharedDatabaseExist = sharedDatabaseFile.exists(); + if (!sharedDatabaseExist) { + + if (log.isInfoEnabled()) { + log.info("Create shared database: " + dbVersion.toString() + "/" + dbName + " to " + sharedDatabaseFile); + } + + DataSourceCreateConfigurationDto createConfiguration = new DataSourceCreateConfigurationDto(); + + String scriptPath = "/db/" + dbVersion.toString() + "/" + dbName + ".sql.gz"; + + byte[] databaseToImportContent = ObserveTestResources.getResourceContent(scriptPath); + + createConfiguration.setImportDatabase(databaseToImportContent); + + observeSwingDataSource = applicationContext.getDataSourcesManager().newDataSource(sharedDatabaseConfiguration); + observeSwingDataSource.create(createConfiguration); + + } + + if (targetPath == null) { + + dataSourceConfiguration = sharedDatabaseConfiguration; + + observeSwingDataSource = applicationContext.getDataSourcesManager().newDataSource(sharedDatabaseConfiguration); + + } else { + + // Use a copy + + dataSourceConfiguration = dataSourcesForTestManager.createDataSourceConfigurationH2(targetPath, dbVersion, dbName, login, password); + File databaseFileTarget = dataSourceConfiguration.getDatabaseFile(); + + if (log.isInfoEnabled()) { + log.info("Copy database: " + dbVersion.toString() + "/" + dbName + " to " + databaseFileTarget); + } + Files.createDirectories(databaseFileTarget.toPath().getParent()); + Files.copy(sharedDatabaseFile.toPath(), databaseFileTarget.toPath()); + + observeSwingDataSource = applicationContext.getDataSourcesManager().newDataSource(sharedDatabaseConfiguration); + + } + + dataSourceConfiguration.setModelVersion(ObserveTestConfiguration.getModelVersion()); + + if (!observeSwingDataSource.isOpen()) { + observeSwingDataSource.open(); + } + return observeSwingDataSource; + + } + + @Override + protected void before(Description description) throws Exception { + super.before(description); + + if (ObserveSwingApplicationContext.isInit()) { + + ObserveSwingApplicationContext.get().close(); + } + + ClientConfig config = new ClientConfig(); + + config.setDataDirectory(getTestDirectory()); + config.initConfig(new ObserveResourceManager().getResource(ObserveResourceManager.Resource.application)); + + ObserveRunner.setResourceManager(new ObserveResourceManager()); + ObserveRunner.initI18n(config); + +// config.getTemplatesDirectory().mkdirs(); + + applicationContext = new ObserveSwingApplicationContext(config); + + I18n.init(new ClassPathI18nInitializer(), Locale.FRANCE); + + } + + protected void after(Description description) throws IOException { + + super.after(description); + applicationContext.close(); + } + +} ===================================== client/src/test/java/fr/ird/observe/client/ClientTestMethodResource.java ===================================== --- /dev/null +++ b/client/src/test/java/fr/ird/observe/client/ClientTestMethodResource.java @@ -0,0 +1,78 @@ +package fr.ird.observe.client; + +/* + * #%L + * ObServe :: Services ToPIA Implementation + * %% + * Copyright (C) 2008 - 2017 IRD, Code Lutin, Ultreia.io + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.client.db.ObserveSwingDataSource; +import fr.ird.observe.services.configuration.topia.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.test.ObserveTestConfiguration; +import fr.ird.observe.test.TestMethodResourceSupport; +import fr.ird.observe.test.spi.CopyDatabaseConfiguration; +import java.io.File; +import java.util.Objects; +import org.junit.runner.Description; + + +/** + * Created on 18/08/15. + * + * @author Tony Chemit - dev@tchemit.fr + */ +public class ClientTestMethodResource extends TestMethodResourceSupport<ClientTestClassResource> { + + private ObserveSwingDataSource dataSource; + + public ClientTestMethodResource(ClientTestClassResource clientTestClassResource) { + super(clientTestClassResource); + } + + public ObserveSwingDataSource getDataSource() { + return dataSource; + } + + public ObserveDataSourceConfigurationTopiaH2 createDataSourceConfigurationH2(Class<?> testClass, String dbName) { + + return testClassResource.getDataSourcesForTestManager().createDataSourceConfigurationH2( + getTestDirectory(), testClass, dbName, getLogin(), getPassword()); + + } + + @Override + protected void before(Description description) throws Throwable { + + super.before(description); + + Objects.requireNonNull(getDbName(), "Pas de nom de base spécifié"); + Objects.requireNonNull(getDbVersion(), "Pas de version de base spécifié"); + Objects.requireNonNull(getLogin(), "Pas de login spécifié"); + Objects.requireNonNull(getPassword(), "Pas de password spécifié"); + + CopyDatabaseConfiguration copyDatabaseConfiguration = ObserveTestConfiguration.getCopyDatabaseConfigurationAnnotation(testClassMethod, testClassResource.getClassifier()); + boolean useSharedDatabase = copyDatabaseConfiguration == null; + + File databasePath = useSharedDatabase ? null : getTestDirectory().toPath().resolve("localDb").toFile(); + + dataSource = testClassResource.createDataSourceConfiguration(getDbVersion(), getDbName(), databasePath, getLogin(), getPassword()); + + } + +} ===================================== client/src/test/java/fr/ird/observe/client/ClientTestSupport.java ===================================== --- /dev/null +++ b/client/src/test/java/fr/ird/observe/client/ClientTestSupport.java @@ -0,0 +1,51 @@ +package fr.ird.observe.client; + +/*- + * #%L + * ObServe :: Services ToPIA Implementation + * %% + * Copyright (C) 2008 - 2017 IRD, Code Lutin, Ultreia.io + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.test.DatabaseName; +import fr.ird.observe.test.ObserveTestConfiguration; +import fr.ird.observe.test.spi.DatabaseLoginConfiguration; +import fr.ird.observe.test.spi.DatabaseNameConfiguration; +import fr.ird.observe.test.spi.DatabasePasswordConfiguration; +import fr.ird.observe.test.spi.DatabaseVersionConfiguration; +import org.junit.ClassRule; +import org.junit.Rule; + +/** + * Created on 26/12/15. + * + * @author Tony Chemit - dev@tchemit.fr + */ +@DatabaseNameConfiguration(DatabaseName.referentiel) +@DatabaseVersionConfiguration(ObserveTestConfiguration.MODEL_VERSION) +@DatabaseLoginConfiguration() +@DatabasePasswordConfiguration(ObserveTestConfiguration.H2_PASSWORD) +public abstract class ClientTestSupport { + + @ClassRule + public static final ClientTestClassResource TEST_CLASS_RESOURCE = new ClientTestClassResource(); + + @Rule + public final ClientTestMethodResource testMethodResource = new ClientTestMethodResource(TEST_CLASS_RESOURCE); + +} ===================================== client/src/test/java/fr/ird/observe/client/DataSourcesForTestManager.java ===================================== --- /dev/null +++ b/client/src/test/java/fr/ird/observe/client/DataSourcesForTestManager.java @@ -0,0 +1,136 @@ +package fr.ird.observe.client; + +/*- + * #%L + * ObServe :: Services ToPIA Implementation + * %% + * Copyright (C) 2008 - 2017 IRD, Code Lutin, Ultreia.io + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.persistence.migration.ObserveMigrationConfigurationProvider; +import fr.ird.observe.services.configuration.topia.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.test.TestHelper; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.version.Version; + +/** + * Created on 26/12/15. + * + * @author Tony Chemit - dev@tchemit.fr + */ +public class DataSourcesForTestManager { + + /** Logger. */ + private static final Log log = LogFactory.getLog(DataSourcesForTestManager.class); + + /** + * Root path of shared databases. + */ + private static Path sharedDatabasesRootPath; + + private Path getSharedDatabasesRootPath() { + if (sharedDatabasesRootPath == null) { + sharedDatabasesRootPath = TestHelper.getCommonsDir().toPath(); + } + return sharedDatabasesRootPath; + } + + private Path getDatabasePath(Path rootPath, Version dbVersion, String dbName) { + return rootPath.resolve(dbVersion.getValidName()).resolve(dbName); + } + + public ObserveDataSourceConfigurationTopiaH2 createSharedDataSourceConfigurationH2(Version dbVersion, String dbName, String login, char[] password) { + Path databasePath = getDatabasePath(getSharedDatabasesRootPath(), dbVersion, dbName); + return createDataSourceConfigurationH2(databasePath.toFile(), dbVersion, dbName, login, password); + } + + public ObserveDataSourceConfigurationTopiaH2 createDataSourceConfigurationH2(File localDbFile, Version dbVersion, String dbName, String login, char[] password) { + + ObserveDataSourceConfigurationTopiaH2 configurationTopiaH2 = new ObserveDataSourceConfigurationTopiaH2(); + + if (log.isDebugEnabled()) { + log.debug("db directory: " + localDbFile); + } + configurationTopiaH2.setLabel("Commons database#" + dbName); + configurationTopiaH2.setUsername(login); + configurationTopiaH2.setPassword(password); + configurationTopiaH2.setDirectory(localDbFile); + configurationTopiaH2.setDbName("obstuna"); + configurationTopiaH2.setAutoMigrate(true); + configurationTopiaH2.setShowMigrationProgression(true); + configurationTopiaH2.setShowMigrationSql(true); + configurationTopiaH2.setModelVersion(dbVersion); + return configurationTopiaH2; + + } + + public ObserveDataSourceConfigurationTopiaH2 createDataSourceConfigurationH2(File testDirectory, Class<?> testClass, String dbName, String login, char[] password) { + + ObserveDataSourceConfigurationTopiaH2 configurationTopiaH2 = new ObserveDataSourceConfigurationTopiaH2(); + + File localDbFile = new File(testDirectory, dbName); + + if (log.isInfoEnabled()) { + log.info("db directory: " + localDbFile); + } + configurationTopiaH2.setLabel(testClass.getSimpleName() + "#" + dbName); + configurationTopiaH2.setUsername(login); + configurationTopiaH2.setPassword(password); + configurationTopiaH2.setDirectory(localDbFile); + configurationTopiaH2.setDbName("obstuna"); + configurationTopiaH2.setAutoMigrate(true); + configurationTopiaH2.setModelVersion(ObserveMigrationConfigurationProvider.get().getLastVersion()); + return configurationTopiaH2; + + } + + public void clear() throws IOException { + Path sharedDatabasesRootPath = getSharedDatabasesRootPath(); + log.info(String.format("Clear share databases directory: %s", sharedDatabasesRootPath)); + if (Files.exists(sharedDatabasesRootPath)) { + Files.newDirectoryStream(sharedDatabasesRootPath).forEach(this::deleteDirectory); + } + } + + private void deleteDirectory(Path directory) { + try { + log.debug(String.format("Delete directory: %s", directory)); + Files.walk(directory).filter(f->!f.equals(directory)).forEach(f -> { + try { + if (Files.isDirectory(f)) { + deleteDirectory(f); + return; + } + log.debug(String.format("Delete file: %s", f)); + Files.delete(f); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }); + + Files.delete(directory); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} ===================================== client/src/test/java/fr/ird/observe/client/ObserveTextGeneratorTest.java ===================================== --- /dev/null +++ b/client/src/test/java/fr/ird/observe/client/ObserveTextGeneratorTest.java @@ -0,0 +1,57 @@ +package fr.ird.observe.client; + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.client.db.ObserveSwingDataSource; +import fr.ird.observe.client.ui.admin.validate.ValidateModel; +import fr.ird.observe.services.service.actions.validate.DataValidationRequest; +import fr.ird.observe.services.service.actions.validate.ValidateService; +import fr.ird.observe.services.service.actions.validate.ValidationResult; +import fr.ird.observe.test.DatabaseName; +import fr.ird.observe.test.ObserveFixtures; +import fr.ird.observe.test.spi.DatabaseNameConfiguration; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Test; +import org.nuiton.validator.NuitonValidatorScope; + +/** + * Created by tchemit on 14/08/17. + * + * @author Tony Chemit - dev@tchemit.fr + */ +public class ObserveTextGeneratorTest extends ClientTestSupport { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ObserveTextGeneratorTest.class); + + @DatabaseNameConfiguration(DatabaseName.dataForTestSeine) + @Test + public void getValidationReport() { + + ObserveSwingDataSource dataSource = testMethodResource.getDataSource(); + + DataValidationRequest request = new DataValidationRequest(); + request.setDataIds(ImmutableSet.of(ObserveFixtures.TRIP_SEINE_ID_1)); + request.setScopes(ImmutableSet.of(NuitonValidatorScope.ERROR, NuitonValidatorScope.WARNING)); + request.setValidationContext(ValidateService.UPDATE_VALIDATION_CONTEXT); + request.setValidationSpeedEnable(true); + request.setValidationLengthWeightEnable(true); + request.setValidationSpeedMaxValue(TEST_CLASS_RESOURCE.getApplicationContext().getConfig().getValidationSpeedMaxValue()); + + ValidationResult<DataValidationRequest> result = dataSource.getValidateService().validateData(request); + + ValidateModel model = new ValidateModel(); + model.setDecoratorService(TEST_CLASS_RESOURCE.getApplicationContext().getDecoratorService()); + model.setValidationResult(result); + model.setContextName(request.getValidationContext()); + model.addScope(NuitonValidatorScope.ERROR); + model.addScope(NuitonValidatorScope.WARNING); + model.setContextName(request.getValidationContext()); + String content = TEST_CLASS_RESOURCE.getApplicationContext().getTextGenerator().getValidationReport(model); + Assert.assertNotNull(content); + log.info(content); + } + + +} \ No newline at end of file ===================================== client/src/test/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java → client/src/test/java/fr/ird/observe/client/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java ===================================== ===================================== services/src/main/java/fr/ird/observe/services/service/actions/validate/ValidationResult.java ===================================== --- a/services/src/main/java/fr/ird/observe/services/service/actions/validate/ValidationResult.java +++ b/services/src/main/java/fr/ird/observe/services/service/actions/validate/ValidationResult.java @@ -77,6 +77,10 @@ public class ValidationResult<R extends ValidationRequest> implements ObserveDto return ImmutableSet.copyOf(data.stream().filter(d -> type.equals(d.getType())).flatMap(d -> d.getMessages().stream()).collect(Collectors.toSet())); } + public ImmutableSet<ValidationResultDto> getDtosForType(Class type) { + return ImmutableSet.copyOf(data.stream().filter(d -> type.equals(d.getType())).collect(Collectors.toSet())); + } + public ImmutableSet<ValidationResultDtoMessage> getMessagesForId(String id) { return ImmutableSet.copyOf(data.stream().filter(d -> id.equals(d.getId())).flatMap(d -> d.getMessages().stream()).collect(Collectors.toSet())); } @@ -148,5 +152,11 @@ public class ValidationResult<R extends ValidationRequest> implements ObserveDto public Collection<ValidationResultDtoMessage> get(String id) { return data.keySet().stream().filter(d -> id.equals(d.getId())).findFirst().map(data::get).orElse(Collections.emptyList()); } + + public void addMessages(ImmutableSet<ValidationResultDto> data) { + for (ValidationResultDto datum : data) { + this.data.putAll(datum.getReference(), datum.getMessages()); + } + } } } ===================================== test/src/main/java/fr/ird/observe/test/TestClassResourceSupport.java ===================================== --- a/test/src/main/java/fr/ird/observe/test/TestClassResourceSupport.java +++ b/test/src/main/java/fr/ird/observe/test/TestClassResourceSupport.java @@ -98,6 +98,10 @@ public abstract class TestClassResourceSupport implements TestRule { return classifier; } + public File getTestDirectory() { + return testDirectory; + } + public String getServerDbName() { return serverDbName; } @@ -118,7 +122,7 @@ public abstract class TestClassResourceSupport implements TestRule { }; } - protected void before(Description description) { + protected void before(Description description) throws Exception{ Class<?> testClass = description.getTestClass(); if (log.isDebugEnabled()) { View it on GitLab: https://gitlab.com/ultreiaio/ird-observe/commit/f098afe65c8054ecad21c8570b7a... --- View it on GitLab: https://gitlab.com/ultreiaio/ird-observe/commit/f098afe65c8054ecad21c8570b7a... You're receiving this email because of your account on gitlab.com.
participants (1)
-
Tony CHEMIT