All files / src/services mapping-management.service.ts

79.77% Statements 276/346
61.42% Branches 164/267
91.38% Functions 53/58
79.25% Lines 252/318

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879                                7x                   7x 7x 7x   7x     7x 7x   7x 7x 7x 7x 7x   7x           7x     92x 92x 92x 92x       92x 92x     92x   7x 1114x     92x 92x 92x 92x   92x                                           7x       1x 1x   1x 1x       1x 1x       1x 1x                       12x 12x   7x     7x 2x 2x                 7x 1x 1x   1x 1x 2x       1x             7x 1x   2x 2x 2x   2x 1x       7x 2x 2x       2x   3x 1x                     7x         1x     1x     1x       1x 1x 1x                     7x           160x 160x 33x 33x 33x 23x   10x         7x 15x 15x                       15x       15x                       15x   15x 15x 15x   15x           7x       20x 1x     19x           19x 19x               19x   19x             19x       19x               19x           7x 5x                 7x                                                                             7x       79x                 1x       78x           9x     69x 10x   59x       59x   39x 19x   14x     45x 22x         23x   11x     11x   15x         12x 5x   7x   9x                       7x 67x                     7x 7x               7x 7x   7x 7x 4x           4x 2x   2x         5x                     7x 12x 12x   12x 12x 12x 12x 12x 12x                 7x 1x 1x   1x         1x 1x     7x 23x       23x 23x 23x     7x 19x 19x 19x                 7x 2x 4x 4x       2x   2x 2x       2x 2x                 7x   5x 5x 5x 5x 5x                   7x     56x 56x                 56x   56x     56x     56x       47x     47x                 7x       47x       47x       47x                                                       47x 47x             61x 61x 56x               69x 69x 70x 68x 68x       13x   68x 80x 94x     60x 60x 60x                     7x 37x 1x     66x 66x             36x 36x       36x 36x         36x 1x 1x   35x 12x 12x           12x           12x       12x         12x   23x 5x 5x         3x           3x       3x         5x   18x 18x                   7x       1x 1x   1x 1x 1x       1x 1x                       7x       1x                 7x 1x                     7x         1x 1x               7x 1x   7x  
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
 
import {
  ErrorInfo,
  ErrorLevel,
  ErrorScope,
  ErrorType,
} from '../models/error.model';
import {
  IAtlasMappingContainer,
  IValidationsContainer,
} from '../contracts/mapping';
import { LookupTableData, LookupTableUtil } from '../utils/lookup-table-util';
import { MappedField, MappingModel } from '../models/mapping.model';
import { Subject, Subscription } from 'rxjs';
 
import { CommonUtil } from '../utils/common-util';
import { ConfigModel } from '../models/config.model';
import { Field } from '../models/field.model';
import { FieldAction } from '../models/field-action.model';
import { FieldType } from '../contracts/common';
import { MappingDefinition } from '../models/mapping-definition.model';
import { MappingSerializer } from '../utils/mapping-serializer';
import { MappingUtil } from '../utils/mapping-util';
import { Multiplicity } from '../contracts/field-action';
import { PaddingField } from '../models/document-definition.model';
import { TransitionMode } from '../models/transition.model';
import ky from 'ky';
import log from 'loglevel';
 
/**
 * Handles mapping updates. It restores mapping status from backend and reflect in UI,
 * and/or reflect mapping changes caused by the user action made in UI to the backend.
 */
export class MappingManagementService {
  _cfg!: ConfigModel;
 
  lineRefreshSource = new Subject<void>();
  lineRefresh$ = this.lineRefreshSource.asObservable();
  mappingUpdatedSource = new Subject<void>();
  mappingUpdated$ = this.mappingUpdatedSource.asObservable();
 
  debugMappingUpdatedSubscription?: Subscription;
 
  mappingSelectionRequiredSource = new Subject<Field>();
  mappingSelectionRequired$ =
    this.mappingSelectionRequiredSource.asObservable();
 
  constructor(private api: typeof ky) {}
 
  get cfg() {
    return this._cfg;
  }
 
  set cfg(cfg: ConfigModel) {
    this._cfg = cfg;
    Eif (!this._cfg.logger) {
      this._cfg.logger = log.getLogger('mapping-management');
    }
    Iif (this._cfg.logger.getLevel() <= this._cfg.logger.levels.DEBUG) {
      this.mappingUpdated$.subscribe(() => {
        if (!this.cfg.mappings) {
          return;
        }
        if (this.cfg.mappings && this.cfg.mappings.activeMapping) {
          this.cfg.logger!.info(
            'mapping updated: ' +
              JSON.stringify(MappingSerializer.serializeMappings(this.cfg))
          );
        }
      });
    }
  }
 
  /**
   * Retrieve current mapping definition JSON file from backend, deserialize it and
   * load it into AtlasMap UI.
   *
   * @param mappingDefinition {@link MappingDefinition}
   * @returns
   */
  fetchMappings(
    _mappingFiles: string[],
    mappingDefinition: MappingDefinition
  ): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      this.cfg.fileService
        .getCurrentMappingJson()
        .then(async (mappingJson: any) => {
          Iif (!mappingJson) {
            resolve(false);
            return;
          }
          this.cfg.mappings = mappingDefinition;
          MappingSerializer.deserializeMappingServiceJSON(
            mappingJson,
            this.cfg
          );
          this.updateMappingsTransition();
          resolve(true);
        })
        .catch((error) => {
          this.cfg.errorService.addBackendError(
            'Failed to load mapping definition from backend:',
            error
          );
          resolve(false);
        });
    });
  }
 
  updateMappingsTransition() {
    this.cfg
      .mappings!.getAllMappings(true)
      .forEach((m) => this.updateTransition(m)); // TODO: check this non null operator
  }
 
  updateActiveMappingTransition() {
    Eif (this.cfg.mappings?.activeMapping) {
      this.updateTransition(this.cfg.mappings?.activeMapping);
    }
  }
 
  /**
   * Remove the specified mapping model from the mappings array and update the runtime.
   *
   * @param mappingModel
   */
  async removeMapping(mappingModel: MappingModel): Promise<boolean> {
    return new Promise<boolean>(async (resolve) => {
      const mappingWasRemoved: boolean =
        this.cfg.mappings!.removeMapping(mappingModel); // TODO: check this non null operator
      if (ImappingWasRemoved) {
        this.deselectMapping();
        await this.notifyMappingUpdated();
      } else {
        this.deselectMapping();
      }
      resolve(true);
    });
  }
 
  /**
   * Remove all mappings from the current session.
   */
  async removeAllMappings(): Promise<boolean> {
    return new Promise<boolean>(async (resolve) => {
      // TODO: check these non null operator on the mappings
      for (const mapping of this.cfg.mappings!.getAllMappings(true)) {
        this.cfg.mappings!.removeMapping(mapping);
        this.deselectMapping();
      }
      await this.notifyMappingUpdated();
      resolve(true);
    });
  }
 
  async updateMappedField(mapping: MappingModel): Promise<boolean> {
    return new Promise<boolean>(async (resolve) => {
      Iif (mapping.isEmpty()) {
        this.cfg.mappings!.removeMapping(mapping); // TODO: check this non null operator
        this.deselectMapping();
      } else {
        this.updateTransition(mapping);
      }
      await this.notifyMappingUpdated();
      resolve(true);
    });
  }
 
  /**
   * Move the specified mapped field in the specified mapping to the specified index.
   *
   * @param mapping
   * @param insertedMappedField
   * @param targetIndex
   */
  moveMappedFieldTo(
    mapping: MappingModel,
    insertedMappedField: MappedField,
    targetIndex: number
  ): void {
    Iif (!mapping || !insertedMappedField) {
      return;
    }
    const mappedFields = mapping.getMappedFields(
      insertedMappedField.isSource()
    );
    mappedFields.splice(
      mapping.getIndexForMappedField(insertedMappedField)! - 1,
      1
    );
    mappedFields.splice(targetIndex - 1, 0, insertedMappedField);
    this.clearExtraPaddingFields(mappedFields, true);
    this.notifyMappingUpdated();
  }
 
  /**
   * Given an index range, fill in the mappings gap with place-holder fields.
   *
   * @param count - number of padding fields to add
   * @param mapping - mapping to modify
   * @param basePadIndex - 0 based
   * @param isSource
   */
  addPlaceholders(
    count: number,
    mapping: MappingModel,
    basePadIndex: number,
    isSource: boolean
  ) {
    let padField = null;
    for (let i = 0; i < count; i++) {
      padField = new MappedField();
      padField.field = new PaddingField(isSource);
      if (isSource) {
        mapping.sourceFields.splice(basePadIndex + i, 0, padField);
      } else {
        mapping.targetFields.splice(basePadIndex + i, 0, padField);
      }
    }
  }
 
  addFieldToActiveMapping(field: Field): void {
    let mapping: MappingModel | null = this.cfg.mappings!.activeMapping;
    Iif (!mapping) {
      this.cfg.errorService.addError(
        new ErrorInfo({
          message: `No mapping is selected to add a field '${field.name}'`,
          level: ErrorLevel.ERROR,
          scope: ErrorScope.MAPPING,
          type: ErrorType.USER,
        })
      );
      return;
    }
 
    const exclusionReason = this.getFieldSelectionExclusionReason(
      mapping,
      field
    );
    Iif (exclusionReason != null) {
      this.cfg.errorService.addError(
        new ErrorInfo({
          message: `The field '${field.name}' cannot be selected, ${exclusionReason}.`,
          level: ErrorLevel.ERROR,
          mapping: mapping,
          scope: ErrorScope.MAPPING,
          type: ErrorType.USER,
        })
      );
      return;
    }
    mapping.addField(field, false);
 
    this.updateTransition(mapping);
    Eif (mapping.sourceFields.length > 0 || mapping.targetFields.length > 0) {
      this.notifyMappingUpdated();
    }
    return;
  }
 
  /**
   * @FIXME Migrate with isFieldAddableToActiveMapping() - https://github.com/atlasmap/atlasmap/issues/3442
   */
  getFieldSelectionExclusionReason(
    mapping: MappingModel,
    field: Field
  ): string | null {
    if (!field.isTerminal()) {
      return 'field is a parent field';
    }
 
    Iif (mapping.getAllMappedFields().length === 0) {
      // if mapping hasn't had a field selected yet, allow it
      return null;
    }
 
    // Non-collection target fields may only be mapped once.
    const existingMappedField = mapping.getMappedTarget(field);
    Iif (existingMappedField != null && !field.isInCollection) {
      return (
        'it is already the target of another mapping (' +
        existingMappedField +
        '). '
      );
    }
 
    const lookupMode: boolean = mapping.isLookupMode();
 
    Iif (lookupMode) {
      if (!field.enumeration) {
        return 'only Enumeration fields are valid for this mapping';
      }
      return null;
    }
    // enums are not selectable in these modes
    Iif (field.enumeration) {
      return 'Enumeration fields are not valid for this mapping';
    }
    // Expression mapping
    Iif (
      mapping.transition.enableExpression &&
      !field.isSource() &&
      mapping.getMappedFields(false).length > 0
    ) {
      return 'cannot add multiple target fields when conditional mapping is enabled.';
    }
 
    return null;
  }
 
  /**
   * @FIXME Migrate with isFieldAddableToActiveMapping() - https://github.com/atlasmap/atlasmap/issues/3442
   */
  isFieldSelectable(mapping: MappingModel, field: Field): boolean {
    return this.getFieldSelectionExclusionReason(mapping, field) == null;
  }
 
  /**
   * Return true if it's possible to add a source or target field to the active
   * mapping, false otherwise.
   * @param isSource true if it's source field, or false
   * @returns
   */
  canAddToActiveMapping(isSource: boolean): boolean {
    const selectedMapping = this.cfg.mappings?.activeMapping;
    if (
      !selectedMapping ||
      (selectedMapping.transition.mode === TransitionMode.ENUM &&
        selectedMapping.sourceFields.length > 0 &&
        selectedMapping.targetFields.length > 0)
    ) {
      return false;
    }
    if (
      selectedMapping.sourceFields.length <= 1 &&
      selectedMapping.targetFields.length <= 1
    ) {
      return true;
    } else if (
      isSource &&
      (selectedMapping.targetFields.length <= 1 ||
        selectedMapping.sourceFields.length === 0)
    ) {
      return true;
    } else if (
      !isSource &&
      (selectedMapping.sourceFields.length <= 1 ||
        selectedMapping.targetFields.length === 0)
    ) {
      return true;
    }
    return false;
  }
 
  /**
   * Return true if it's possible to add the specified field to the
   * specified mapping, or if it's possible to create a new mapping
   * with the specified field when the specified mapping is null or undefined,
   * false otherwise.
   * @param field field
   * @param mapping a mapping to add the field
   */
  isFieldAddableToMapping(
    field: Field,
    mapping?: MappingModel | null
  ): boolean {
    if (
      !field ||
      !field.isTerminal() ||
      field.type === FieldType.UNSUPPORTED ||
      (mapping &&
        mapping.transition.mode === TransitionMode.ENUM &&
        mapping.sourceFields.length > 0 &&
        mapping.targetFields.length > 0)
    ) {
      return false;
    }
 
    // non-collection target field can't participate to more than one mapping
    if (
      !field.isSource() &&
      !field.isCollection &&
      !field.isInCollection() &&
      this.cfg.mappings?.findMappingsForField(field).length !== 0
    ) {
      return false;
    }
 
    if (!mapping) {
      return true;
    }
    Iif (mapping.transition.mode === TransitionMode.EXPRESSION) {
      return field.isSource() || mapping.targetFields.length === 0;
    }
    // skip if already in the mapping
    if (
      (field.isSource() &&
        mapping.sourceFields.find((f) => f.field === field)) ||
      (!field.isSource() && mapping.targetFields.find((f) => f.field === field))
    ) {
      return false;
    }
    // adding a collection field
    if (field.isCollection || field.isInCollection()) {
      return field.isSource()
        ? mapping.sourceFields.length === 0
        : mapping.targetFields.length === 0;
    }
 
    if (field.isSource()) {
      // adding a source non-collection field
      Iif (mapping.sourceFields.length === 0) {
        return true;
      }
      return (
        !mapping.sourceFields.find(
          (f) => f.field?.isCollection || f.field?.isInCollection()
        ) && mapping.targetFields.length <= 1
      );
    } else {
      // adding a target non-collection field
      if (mapping.targetFields.length === 0) {
        return true;
      }
      return (
        !mapping.targetFields.find(
          (f) => f.field?.isCollection || f.field?.isInCollection()
        ) && mapping.sourceFields.length <= 1
      );
    }
  }
 
  /**
   * Return true if it's possible to add the specified source field to the
   * active mapping, false otherwise.
   * @param field field
   * @param dropTarget a destination field to drop if it's drag & drop
   */
  isFieldAddableToActiveMapping(field: Field): boolean {
    return this.isFieldAddableToMapping(
      field,
      this.cfg.mappings?.activeMapping
    );
  }
 
  /**
   * Return true if it's possible to drag a field to the destination field, false otherwise.
   * @param src dragging field
   * @param dest a destination field to drop
   */
  isFieldDragAndDropAllowed(src?: Field, dest?: Field): boolean {
    Iif (
      !src ||
      !dest ||
      (src.isSource() && dest.isSource()) ||
      (!src.isSource() && !dest.isSource())
    ) {
      return false;
    }
    const source = src.isSource() ? src : dest;
    const target = src.isSource() ? dest : src;
 
    const activeMapping = this.cfg.mappings?.activeMapping;
    if (activeMapping) {
      Iif (
        activeMapping.isFieldMapped(source) &&
        activeMapping.isFieldMapped(target)
      ) {
        return false;
      }
      if (activeMapping.isFieldMapped(source)) {
        return this.isFieldAddableToMapping(target, activeMapping);
      }
      Iif (activeMapping.isFieldMapped(target)) {
        return this.isFieldAddableToMapping(source, activeMapping);
      }
    }
    // It'll create a new mapping
    return (
      this.isFieldAddableToMapping(source, null) &&
      this.isFieldAddableToMapping(target, null)
    );
  }
 
  /**
   * Instantiate a new mapping model and associate the selected field with it.
   * @param selectedField
   * @param compoundSelection - indicates a compound-selection (ctrl/cmd-M1) if true, standard mouse click if false.
   */
  addNewMapping(selectedField: Field, compoundSelection: boolean): void {
    Eif (!compoundSelection) {
      this.deselectMapping();
    }
    const mapping: MappingModel = new MappingModel();
    Eif (selectedField != null) {
      mapping.addField(selectedField, false);
      this.updateTransition(mapping);
      this.selectMapping(mapping);
      this.notifyMappingUpdated();
    } else {
      this.selectMapping(mapping);
    }
  }
 
  /**
   * Instantiate a new mapping model.
   */
  newMapping(): void {
    this.deselectMapping();
    const mapping: MappingModel = new MappingModel();
    // Determine type of mapping (i.e., transition mode)
    this.updateTransition(mapping);
    // SelectMapping marks new mapping as active mapping, which is necessary so
    // that it gets added to the existing mappings in notifyMappingUpdated().
    // TODO: this seems very unintuitive, seems like some step to explicitly
    // add the new mapping would make more sense
    this.selectMapping(mapping);
    this.notifyMappingUpdated();
  }
 
  selectMapping(mappingModel: MappingModel) {
    Iif (mappingModel == null) {
      this.deselectMapping();
      return;
    }
    this.cfg.mappings!.activeMapping = mappingModel; // TODO: check this non null operator
    this.cfg.showMappingDetailTray = true;
    this.mappingUpdatedSource.next();
  }
 
  deselectMapping(): void {
    this.cfg.showMappingDetailTray = false;
    this.cfg.mappings!.activeMapping = null; // TODO: check this non null operator
    this.notifyMappingUpdated();
  }
 
  /**
   * Remove any mappings referencing the specified document ID.
   *
   * @param docId - Specified document ID
   * @param cfg
   */
  removeDocumentReferenceFromAllMappings(docId: string) {
    for (const mapping of this.cfg.mappings!.getAllMappings(true)) {
      for (const mappedField of mapping.getAllFields()) {
        if (
          mappedField instanceof PaddingField ||
          mappedField.docDef.id !== docId
        ) {
          continue;
        }
        this.removeFieldFromAllMappings(mappedField);
        Eif (
          mapping.sourceFields.length === 0 ||
          mapping.targetFields.length === 0
        ) {
          this.cfg.mappings!.removeMapping(mapping); // TODO: check this non null operator
          Iif (mapping === this.cfg.mappings!.activeMapping) {
            // TODO: check this non null operator
            this.cfg.mappingService.deselectMapping();
          }
        }
      }
    }
  }
 
  removeFieldFromAllMappings(field: Field): void {
    // TODO: check this non null operator
    for (const mapping of this.cfg.mappings!.getAllMappings(true)) {
      const mappedField = mapping.getMappedFieldForField(field);
      Eif (mappedField != null) {
        mapping.removeMappedField(mappedField);
        Iif (mapping.isEmpty()) {
          this.cfg.mappings!.removeMapping(mapping); // TODO: check this non null operator
        }
      }
    }
  }
 
  /**
   * Invoke the runtime service to validate the current active mapping.
   */
  private async validateMappings(
    payload: IAtlasMappingContainer
  ): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      Iif (
        this.cfg.initCfg.baseMappingServiceUrl === null ||
        this.cfg.mappings === null
      ) {
        // validation service not configured or required
        resolve(false);
        return;
      }
 
      this.cfg.errorService.clearValidationErrors();
      const url: string =
        this.cfg.initCfg.baseMappingServiceUrl +
        'mapping/validate/' +
        this.cfg.mappingDefinitionId;
      this.cfg.logger!.debug(
        `Validation Service Request: ${JSON.stringify(payload)}\n`
      );
      this.api
        .put(url, { json: payload })
        .json<IValidationsContainer>()
        .then((body) => {
          this.cfg.logger!.debug(
            `Validation Service Response: ${JSON.stringify(body)}\n`
          );
          this.processValidationResponse(body, resolve);
        })
        .catch(() => {
          this.cfg.logger!.warn('Unable to fetch validation data.');
          resolve(false);
        });
    });
  }
 
  private processValidationResponse(
    body: IValidationsContainer,
    resolve: (value: boolean) => void
  ) {
    Iif (this.cfg.mappings === null) {
      resolve(false);
      return;
    }
    const errors: ErrorInfo[] = [];
 
    // This should be eventually turned into mapping entry level validation.
    // https://github.com/atlasmap/atlasmap-ui/issues/116
    Iif (body && body.Validations && body.Validations.validation) {
      for (const validation of body.Validations.validation) {
        const level: ErrorLevel =
          ErrorLevel[validation.status ? validation.status : 'ERROR'];
        let scope: ErrorScope =
          ErrorScope[validation.scope ? validation.scope : 'MAPPING'];
        let validatedMapping: MappingModel | undefined = undefined;
        if (!scope || scope !== ErrorScope.MAPPING || !validation.id) {
          scope = ErrorScope.APPLICATION;
        } else {
          scope = ErrorScope.MAPPING;
          if (this.cfg.mappings && this.cfg.mappings.mappings) {
            validatedMapping = this.cfg.mappings.mappings.find(
              (m) => m.uuid === validation.id
            )!; // TODO: check this non null operator
          }
        }
        errors.push(
          new ErrorInfo({
            message: validation.message,
            level: level,
            scope: scope,
            mapping: validatedMapping,
            type: ErrorType.VALIDATION,
          })
        );
      }
    }
    this.cfg.errorService.addError(...errors);
    resolve(true);
  }
 
  /**
   * Notify the line machine to update the lines between panels.  Most widgets require a
   * small delay to allow the panel to complete forming so add it here.
   */
  notifyLineRefresh(): void {
    setTimeout(() => {
      this.lineRefreshSource.next();
    }, 1);
  }
 
  /**
   * Validate and save complete mappings.  Triggered either as an observable
   * or directly.
   */
  notifyMappingUpdated(): Promise<boolean> {
    return new Promise<boolean>(async (resolve) => {
      if (this.cfg.mappings) {
        const activeMapping: MappingModel = this.cfg.mappings.activeMapping!; // TODO: check this non null operator
        if (
          activeMapping &&
          this.cfg.mappings.mappings.indexOf(activeMapping) === -1
        ) {
          this.cfg.mappings.mappings.push(activeMapping);
        }
        const payload = MappingSerializer.serializeMappings(this.cfg);
        if (await this.validateMappings(payload)) {
          await this.cfg.fileService.setMappingToService(payload);
        }
      }
      this.mappingUpdatedSource.next();
      this.notifyLineRefresh();
      resolve(true);
    });
  }
 
  /**
   * Update mode transition from a single mapping to multiple-mappings and back.
   *
   * @param mapping
   * @param position
   * @param offset
   */
  private updateTransition(mapping: MappingModel): void {
    if (mapping.transition.enableExpression) {
      return;
    }
 
    for (const field of mapping.getAllFields()) {
      Iif (field.enumeration) {
        mapping.transition.mode = TransitionMode.ENUM;
        LookupTableUtil.populateMappingLookupTable(this.cfg.mappings!, mapping); // TODO: check this non null operator
        return;
      }
    }
 
    const sourceMappedFields = mapping.getMappedFields(true);
    const sourceMappedCollection = MappingUtil.hasMappedCollection(
      mapping,
      true
    );
    const targetMappedFields = mapping.getMappedFields(false);
    const targetMappedCollection = MappingUtil.hasMappedCollection(
      mapping,
      false
    );
 
    if (sourceMappedCollection && targetMappedCollection) {
      mapping.transition.mode = TransitionMode.FOR_EACH;
      return;
    }
    if (sourceMappedFields.length > 1 || sourceMappedCollection) {
      mapping.transition.mode = TransitionMode.MANY_TO_ONE;
      Eif (
        !mapping.transition.transitionFieldAction ||
        !mapping.transition.transitionFieldAction.definition ||
        mapping.transition.transitionFieldAction.definition.multiplicity !==
          Multiplicity.MANY_TO_ONE
      ) {
        mapping.transition.transitionFieldAction = FieldAction.create(
          this.cfg.fieldActionService.getActionDefinitionForName(
            'Concatenate',
            Multiplicity.MANY_TO_ONE
          )!
        ); // TODO: check this non null operator
        mapping.transition.transitionFieldAction.setArgumentValue(
          'delimiter',
          ' '
        );
        mapping.transition.transitionFieldAction.setArgumentValue(
          'delimitingEmptyValues',
          'true'
        );
      }
      return;
    }
    if (targetMappedFields.length > 1 || targetMappedCollection) {
      mapping.transition.mode = TransitionMode.ONE_TO_MANY;
      if (
        !mapping.transition.transitionFieldAction ||
        mapping.transition.transitionFieldAction.definition?.multiplicity !==
          Multiplicity.ONE_TO_MANY
      ) {
        mapping.transition.transitionFieldAction = FieldAction.create(
          this.cfg.fieldActionService.getActionDefinitionForName(
            'Split',
            Multiplicity.ONE_TO_MANY
          )!
        ); // TODO: check this non null operator
        mapping.transition.transitionFieldAction.setArgumentValue(
          'delimiter',
          ' '
        );
        mapping.transition.transitionFieldAction.setArgumentValue(
          'collapseRepeatingDelimiters',
          'false'
        );
      }
      return;
    }
    mapping.transition.mode = TransitionMode.ONE_TO_ONE;
    mapping.transition.transitionFieldAction = null;
  }
 
  /**
   * Remove any trailing padding fields for the mapped field array.  This occurs when a user moves
   * a mapped element above the last padding field.
   *
   * @param mappedFields
   * @param trailing - Remove trailing padding fields only
   */
  private clearExtraPaddingFields(
    mappedFields: MappedField[],
    trailing: boolean
  ): void {
    let index = 0;
    let mField = null;
 
    for (index = mappedFields.length - 1; index >= 0; index--) {
      mField = mappedFields[index];
      Iif (mField.isPadField()) {
        CommonUtil.removeItemFromArray(mField, mappedFields);
        continue;
      }
      Eif (trailing) {
        break;
      }
    }
  }
 
  /**
   * Get the enumeration values for the specified mapping and return it in
   * the form of a lookup table.
   *
   * @param cfg
   * @param mapping
   */
  getEnumerationValues(
    cfg: ConfigModel,
    mapping: MappingModel
  ): LookupTableData[] {
    return LookupTableUtil.getEnumerationValues(cfg, mapping);
  }
 
  /**
   * Set the enumeration field value based on the specified enumeration value index.
   *
   * @param enumerationField
   * @param enumerationValue
   */
  setEnumFieldValue(enumerationField: Field, enumerationValue: number) {
    enumerationField.enumIndexValue = enumerationValue;
  }
 
  /**
   * Update the enumeration values for the specified mapping with the specified
   * enumeration values.
   *
   * @param cfg
   * @param mapping
   * @param enumerationValues
   */
  updateEnumerationValues(
    cfg: ConfigModel,
    mapping: MappingModel,
    enumerationValues: LookupTableData[]
  ): void {
    LookupTableUtil.updateEnumerationValues(cfg, mapping, enumerationValues);
    this.notifyMappingUpdated();
  }
 
  /**
   * Return true if the specified mapping is an enumeration mapping, false otherwise.
   *
   * @param mapping
   */
  isEnumerationMapping(mapping: MappingModel): boolean {
    return mapping.transition.mode === TransitionMode.ENUM;
  }
}