Search in sources :

Example 1 with ValidationThreadPool

use of com.b2international.snowowl.core.internal.validation.ValidationThreadPool in project snow-owl by b2ihealthcare.

the class ValidateRequest method doValidate.

private ValidationResult doValidate(BranchContext context, Writer index) throws IOException {
    final String branchPath = context.path();
    ValidationRuleSearchRequestBuilder req = ValidationRequests.rules().prepareSearch();
    TerminologyResource resource = context.service(TerminologyResource.class);
    ResourceURI resourceURI = resource.getResourceURI(branchPath);
    if (!CompareUtils.isEmpty(ruleIds)) {
        req.filterByIds(ruleIds);
    }
    final ValidationRules rules = req.all().build().execute(context);
    final ValidationThreadPool pool = context.service(ValidationThreadPool.class);
    final BlockingQueue<IssuesToPersist> issuesToPersistQueue = Queues.newLinkedBlockingDeque();
    final List<Promise<Object>> validationPromises = Lists.newArrayList();
    // evaluate selected rules
    for (ValidationRule rule : rules) {
        checkArgument(rule.getCheckType() != null, "CheckType is missing for rule " + rule.getId());
        final ValidationRuleEvaluator evaluator = ValidationRuleEvaluator.Registry.get(rule.getType());
        if (evaluator != null) {
            validationPromises.add(pool.submit(rule.getCheckType(), () -> {
                Stopwatch w = Stopwatch.createStarted();
                try {
                    LOG.info("Executing rule '{}'...", rule.getId());
                    final List<?> evaluationResponse = evaluator.eval(context, rule, ruleParameters);
                    issuesToPersistQueue.offer(new IssuesToPersist(rule.getId(), evaluationResponse));
                    LOG.info("Execution of rule '{}' successfully completed in '{}'.", rule.getId(), w);
                // TODO report successfully executed validation rule
                } catch (Exception e) {
                    // TODO report failed validation rule
                    LOG.error("Execution of rule '{}' failed after '{}'.", rule.getId(), w, e);
                }
            }));
        }
    }
    final Set<String> ruleIds = rules.stream().map(ValidationRule::getId).collect(Collectors.toSet());
    final Multimap<String, ComponentIdentifier> whiteListedEntries = fetchWhiteListEntries(context, ruleIds);
    final Promise<List<Object>> promise = Promise.all(validationPromises);
    while (!promise.isDone() || !issuesToPersistQueue.isEmpty()) {
        if (!issuesToPersistQueue.isEmpty()) {
            final Collection<IssuesToPersist> issuesToPersist = newArrayList();
            issuesToPersistQueue.drainTo(issuesToPersist);
            if (!issuesToPersist.isEmpty()) {
                final List<String> rulesToPersist = issuesToPersist.stream().map(itp -> itp.ruleId).collect(Collectors.toList());
                LOG.info("Persisting issues generated by rules '{}'...", rulesToPersist);
                // persist new issues generated by rules so far, extending them using the Issue Extension API
                int persistedIssues = 0;
                final Multimap<String, ValidationIssue> issuesToExtendWithDetailsByToolingId = HashMultimap.create();
                for (IssuesToPersist ruleIssues : Iterables.consumingIterable(issuesToPersist)) {
                    final String ruleId = ruleIssues.ruleId;
                    final List<ValidationIssue> existingRuleIssues = ValidationRequests.issues().prepareSearch().all().filterByResourceUri(resourceURI).filterByRule(ruleId).build().execute(context).getItems();
                    final Set<String> issueIdsToDelete = Sets.newHashSet();
                    final Map<ComponentIdentifier, ValidationIssue> existingIsssuesByComponentIdentifier = new HashMap<>();
                    for (ValidationIssue issue : existingRuleIssues) {
                        if (existingIsssuesByComponentIdentifier.containsKey(issue.getAffectedComponent())) {
                            issueIdsToDelete.add(issue.getId());
                        } else {
                            existingIsssuesByComponentIdentifier.put(issue.getAffectedComponent(), issue);
                        }
                    }
                    // remove all processed whitelist entries
                    final Collection<ComponentIdentifier> ruleWhiteListEntries = whiteListedEntries.removeAll(ruleId);
                    final String toolingId = rules.stream().filter(rule -> ruleId.equals(rule.getId())).findFirst().get().getToolingId();
                    for (ValidationIssueDetails issueDetails : ruleIssues.issueDetails) {
                        final ValidationIssue validationIssue;
                        ComponentIdentifier componentIdentifier = issueDetails.affectedComponentId;
                        if (!existingIsssuesByComponentIdentifier.containsKey(componentIdentifier)) {
                            validationIssue = new ValidationIssue(UUID.randomUUID().toString(), ruleId, ComponentURI.of(resourceURI, componentIdentifier), ruleWhiteListEntries.contains(componentIdentifier));
                        } else {
                            final ValidationIssue issueToCopy = existingIsssuesByComponentIdentifier.get(componentIdentifier);
                            validationIssue = new ValidationIssue(issueToCopy.getId(), issueToCopy.getRuleId(), ComponentURI.of(resourceURI, issueToCopy.getAffectedComponent()), ruleWhiteListEntries.contains(issueToCopy.getAffectedComponent()));
                            existingIsssuesByComponentIdentifier.remove(componentIdentifier);
                        }
                        validationIssue.setDetails(ValidationIssueDetails.HIGHLIGHT_DETAILS, issueDetails.stylingDetails);
                        issuesToExtendWithDetailsByToolingId.put(toolingId, validationIssue);
                        persistedIssues++;
                    }
                    existingRuleIssues.stream().filter(issue -> existingIsssuesByComponentIdentifier.containsKey(issue.getAffectedComponent())).forEach(issue -> issueIdsToDelete.add(issue.getId()));
                    if (!issueIdsToDelete.isEmpty()) {
                        index.removeAll(Collections.singletonMap(ValidationIssue.class, issueIdsToDelete));
                    }
                }
                for (String toolingId : issuesToExtendWithDetailsByToolingId.keySet()) {
                    final ValidationIssueDetailExtension extensions = context.service(ValidationIssueDetailExtensionProvider.class).getExtensions(toolingId);
                    final Collection<ValidationIssue> issues = issuesToExtendWithDetailsByToolingId.removeAll(toolingId);
                    extensions.extendIssues(context, issues, ruleParameters);
                    for (ValidationIssue issue : issues) {
                        index.put(issue);
                    }
                }
                index.commit();
                LOG.info("Persisted '{}' issues generated by rules '{}'.", persistedIssues, rulesToPersist);
            }
        } else {
            try {
                // wait at least number of rules * 50ms for the next responses
                Thread.sleep(Math.min(((long) ruleIds.size()) * 100, POLL_INTERVAL_MAX));
            } catch (InterruptedException e) {
                throw new SnowowlRuntimeException(e);
            }
        }
    }
    // TODO return ValidationResult object with status and new issue IDs as set
    return new ValidationResult(context.info().id(), context.path());
}
Also used : ValidationIssueDetailExtensionProvider(com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtensionProvider) java.util(java.util) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) Stopwatch(com.google.common.base.Stopwatch) Promise(com.b2international.snowowl.core.events.util.Promise) LoggerFactory(org.slf4j.LoggerFactory) ValidationIssue(com.b2international.snowowl.core.validation.issue.ValidationIssue) ValidationIssueDetailExtension(com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtension) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) AccessControl(com.b2international.snowowl.core.authorization.AccessControl) Permission(com.b2international.snowowl.core.identity.Permission) CompareUtils(com.b2international.commons.CompareUtils) ValidationRuleSearchRequestBuilder(com.b2international.snowowl.core.validation.rule.ValidationRuleSearchRequestBuilder) com.google.common.collect(com.google.common.collect) ValidationRepository(com.b2international.snowowl.core.internal.validation.ValidationRepository) ResourceURI(com.b2international.snowowl.core.ResourceURI) ValidationRule(com.b2international.snowowl.core.validation.rule.ValidationRule) ValidationWhiteListSearchRequestBuilder(com.b2international.snowowl.core.validation.whitelist.ValidationWhiteListSearchRequestBuilder) ValidationThreadPool(com.b2international.snowowl.core.internal.validation.ValidationThreadPool) Logger(org.slf4j.Logger) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Request(com.b2international.snowowl.core.events.Request) ComponentURI(com.b2international.snowowl.core.uri.ComponentURI) IOException(java.io.IOException) BlockingQueue(java.util.concurrent.BlockingQueue) Collectors(java.util.stream.Collectors) Writer(com.b2international.index.Writer) ValidationRuleEvaluator(com.b2international.snowowl.core.validation.eval.ValidationRuleEvaluator) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ComponentIdentifier(com.b2international.snowowl.core.ComponentIdentifier) ValidationRules(com.b2international.snowowl.core.validation.rule.ValidationRules) BranchContext(com.b2international.snowowl.core.domain.BranchContext) ValidationRuleSearchRequestBuilder(com.b2international.snowowl.core.validation.rule.ValidationRuleSearchRequestBuilder) ValidationThreadPool(com.b2international.snowowl.core.internal.validation.ValidationThreadPool) Stopwatch(com.google.common.base.Stopwatch) ComponentIdentifier(com.b2international.snowowl.core.ComponentIdentifier) ValidationIssueDetailExtension(com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtension) TerminologyResource(com.b2international.snowowl.core.TerminologyResource) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ResourceURI(com.b2international.snowowl.core.ResourceURI) ValidationIssue(com.b2international.snowowl.core.validation.issue.ValidationIssue) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) IOException(java.io.IOException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) ValidationRule(com.b2international.snowowl.core.validation.rule.ValidationRule) Promise(com.b2international.snowowl.core.events.util.Promise) ValidationRules(com.b2international.snowowl.core.validation.rule.ValidationRules) ValidationRuleEvaluator(com.b2international.snowowl.core.validation.eval.ValidationRuleEvaluator) ValidationIssueDetailExtensionProvider(com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtensionProvider)

Example 2 with ValidationThreadPool

use of com.b2international.snowowl.core.internal.validation.ValidationThreadPool in project snow-owl by b2ihealthcare.

the class SnomedValidationIssueDetailTest method setup.

@Before
public void setup() {
    final Index index = Indexes.createIndex(UUID.randomUUID().toString(), getMapper(), new Mappings(ValidationRule.class, ValidationIssue.class, ValidationWhiteList.class));
    repository = new ValidationRepository(index);
    ClassPathScanner scanner = new ClassPathScanner("com.b2international");
    context = TestBranchContext.on(MAIN).with(ObjectMapper.class, getMapper()).with(EclParser.class, new DefaultEclParser(INJECTOR.getInstance(IParser.class), INJECTOR.getInstance(IResourceValidator.class))).with(EclSerializer.class, new DefaultEclSerializer(INJECTOR.getInstance(ISerializer.class))).with(Index.class, rawIndex()).with(RevisionIndex.class, index()).with(ValidationThreadPool.class, new ValidationThreadPool(1, 1, 1)).with(ValidationRepository.class, repository).with(ClassPathScanner.class, scanner).with(ValidationIssueDetailExtensionProvider.class, new ValidationIssueDetailExtensionProvider(scanner)).with(ResourceURIPathResolver.class, ResourceURIPathResolver.fromMap(Map.of("SNOMEDCT", Branch.MAIN_PATH))).build();
    evaluator = new SnomedQueryValidationRuleEvaluator();
    if (!ValidationRuleEvaluator.Registry.types().contains(evaluator.type())) {
        ValidationRuleEvaluator.Registry.register(evaluator);
    }
    context.service(ValidationIssueDetailExtensionProvider.class).addExtension(new SnomedValidationIssueDetailExtension());
}
Also used : ValidationRepository(com.b2international.snowowl.core.internal.validation.ValidationRepository) RevisionIndex(com.b2international.index.revision.RevisionIndex) DefaultEclSerializer(com.b2international.snowowl.snomed.core.ecl.DefaultEclSerializer) ValidationThreadPool(com.b2international.snowowl.core.internal.validation.ValidationThreadPool) RevisionIndex(com.b2international.index.revision.RevisionIndex) Index(com.b2international.index.Index) DefaultEclSerializer(com.b2international.snowowl.snomed.core.ecl.DefaultEclSerializer) EclSerializer(com.b2international.snowowl.snomed.core.ecl.EclSerializer) ValidationIssue(com.b2international.snowowl.core.validation.issue.ValidationIssue) ValidationWhiteList(com.b2international.snowowl.core.validation.whitelist.ValidationWhiteList) ValidationRule(com.b2international.snowowl.core.validation.rule.ValidationRule) DefaultEclParser(com.b2international.snowowl.snomed.core.ecl.DefaultEclParser) Mappings(com.b2international.index.mapping.Mappings) ValidationIssueDetailExtensionProvider(com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtensionProvider) ClassPathScanner(com.b2international.snowowl.core.plugin.ClassPathScanner) SnomedValidationIssueDetailExtension(com.b2international.snowowl.snomed.validation.detail.SnomedValidationIssueDetailExtension) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ISerializer(org.eclipse.xtext.serializer.ISerializer) Before(org.junit.Before)

Example 3 with ValidationThreadPool

use of com.b2international.snowowl.core.internal.validation.ValidationThreadPool in project snow-owl by b2ihealthcare.

the class BaseValidationTest method setup.

@Before
public final void setup() {
    final ClassPathScanner scanner = new ClassPathScanner("com.b2international");
    Builder context = TestBranchContext.on(MAIN).with(ClassLoader.class, getClass().getClassLoader()).with(ClassPathScanner.class, scanner).with(Index.class, rawIndex()).with(RevisionIndex.class, index()).with(ObjectMapper.class, getMapper()).with(ValidationRepository.class, new ValidationRepository(rawIndex())).with(ValidationThreadPool.class, new ValidationThreadPool(1, 1, 1)).with(ValidationIssueDetailExtensionProvider.class, new ValidationIssueDetailExtensionProvider(scanner)).with(TerminologyRegistry.class, TerminologyRegistry.INSTANCE).with(ResourceURIPathResolver.class, ResourceURIPathResolver.fromMap(getTestCodeSystemPathMap())).with(ScriptEngine.Registry.class, new ScriptEngine.Registry(scanner));
    configureContext(context);
    this.context = context.build();
    initializeData();
}
Also used : ValidationRepository(com.b2international.snowowl.core.internal.validation.ValidationRepository) RevisionIndex(com.b2international.index.revision.RevisionIndex) ValidationIssueDetailExtensionProvider(com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtensionProvider) ValidationThreadPool(com.b2international.snowowl.core.internal.validation.ValidationThreadPool) ValidateRequestBuilder(com.b2international.snowowl.core.validation.ValidateRequestBuilder) Builder(com.b2international.snowowl.test.commons.snomed.TestBranchContext.Builder) ResourceURIPathResolver(com.b2international.snowowl.core.uri.ResourceURIPathResolver) ClassPathScanner(com.b2international.snowowl.core.plugin.ClassPathScanner) ScriptEngine(com.b2international.snowowl.core.scripts.ScriptEngine) Before(org.junit.Before)

Aggregations

ValidationRepository (com.b2international.snowowl.core.internal.validation.ValidationRepository)3 ValidationThreadPool (com.b2international.snowowl.core.internal.validation.ValidationThreadPool)3 ValidationIssueDetailExtensionProvider (com.b2international.snowowl.core.validation.issue.ValidationIssueDetailExtensionProvider)3 RevisionIndex (com.b2international.index.revision.RevisionIndex)2 ClassPathScanner (com.b2international.snowowl.core.plugin.ClassPathScanner)2 ValidationIssue (com.b2international.snowowl.core.validation.issue.ValidationIssue)2 ValidationRule (com.b2international.snowowl.core.validation.rule.ValidationRule)2 CompareUtils (com.b2international.commons.CompareUtils)1 Index (com.b2international.index.Index)1 Writer (com.b2international.index.Writer)1 Mappings (com.b2international.index.mapping.Mappings)1 ComponentIdentifier (com.b2international.snowowl.core.ComponentIdentifier)1 ResourceURI (com.b2international.snowowl.core.ResourceURI)1 TerminologyResource (com.b2international.snowowl.core.TerminologyResource)1 SnowowlRuntimeException (com.b2international.snowowl.core.api.SnowowlRuntimeException)1 AccessControl (com.b2international.snowowl.core.authorization.AccessControl)1 BranchContext (com.b2international.snowowl.core.domain.BranchContext)1 Request (com.b2international.snowowl.core.events.Request)1 Promise (com.b2international.snowowl.core.events.util.Promise)1 Permission (com.b2international.snowowl.core.identity.Permission)1