All files / src/models document-definition.model.ts

86.39% Statements 254/294
65% Branches 65/100
75% Functions 27/36
86.9% Lines 219/252

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                              14x             14x   14x     14x           29x 29x   14x 1x 1x 1x 1x   1x     14x 1x     1x               14x           14x     14x   14x 33x 33x 33x 33x 33x 33x 33x     14x     14x   14x     558x 558x                               558x 558x 558x 558x 558x 558x 558x 558x 558x 558x 558x 558x       14x 501x 501x         2880x     14x 29x     14x       14x 59x                   14x                             14x               14x                     14x 4x 4x 1x 1x 1x     4x     14x         14x 468x     468x   468x 468x   468x 468x   468x 1x 1x 1x       1x 1x 1x 1x 1x     1x                             1x   468x     14x 6x     14x 6x     14x 102x 21x     102x   265x 265x 265x 265x     102x 102x     14x 2x 2x         1x 1x   1x   2x 2x     14x 643x 534x 534x   109x 109x 109x   643x 643x 643x             14x   374x 345x     29x 29x 25x       4x 14x 14x 14x 14x 14x 14x     4x 3x 3x   1x       14x 14x 14x 14x 14x               14x 435x 435x 435x 435x 435x 435x 435x 435x 435x     14x 6x 6x 6x                     14x 2x     2x 2x 2x   2x 2x 2x   2x 2x 2x   2x 2x 2x 2x         14x 54x 2x     492x 492x 492x 492x       52x 20x 20x     20x 20x 30x 30x   30x       492x 492x       14x 1420x 1420x 1420x 1420x   1420x 2x   1420x 1215x   496x 496x 496x         14x 21x     21x   21x 18x     18x   148x 148x     18x       14x 16x   32x 10x             10x 10x         16x     14x 265x 265x 224x   41x 18x     41x 41x       14x  
/*
    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 {
  DocumentType,
  FIELD_PATH_SEPARATOR,
  FieldType,
  InspectionType,
} from '../contracts/common';
 
import { CommonUtil } from '../utils/common-util';
import { DocumentInitializationModel } from './config.model';
import { Field } from './field.model';
import { MappingDefinition } from './mapping-definition.model';
 
export class NamespaceModel {
  private static unqualifiedNamespace: NamespaceModel;
 
  alias: string;
  uri: string;
  locationUri: string | undefined;
  createdByUser = false;
  isTarget = false;
 
  static getUnqualifiedNamespace(): NamespaceModel {
    Eif (NamespaceModel.unqualifiedNamespace == null) {
      const ns: NamespaceModel = new NamespaceModel();
      ns.alias = 'Unqualified';
      NamespaceModel.unqualifiedNamespace = ns;
    }
    return NamespaceModel.unqualifiedNamespace;
  }
 
  getPrettyLabel(): string {
    Iif (this === NamespaceModel.getUnqualifiedNamespace()) {
      return this.alias;
    }
    return (
      (this.isTarget ? 'Target' : this.alias) +
      ' [' +
      (this.uri == null ? 'NO URI' : this.uri) +
      ']'
    );
  }
 
  copy(): NamespaceModel {
    const copy: NamespaceModel = new NamespaceModel();
    Object.assign(copy, this);
    return copy;
  }
 
  copyFrom(that: NamespaceModel): void {
    Object.assign(this, that);
  }
}
 
export class PaddingField extends Field {
  constructor(private _isSource: boolean) {
    super();
    this.name = '<padding field>';
    this.classIdentifier = '<padding field>';
    this.type = FieldType.NONE;
    this.displayName = '<padding field>';
    this.path = '';
  }
 
  isSource(): boolean {
    return this._isSource;
  }
}
 
export class DocumentDefinition {
  private static padField: Field;
 
  LEFT_BRACKET = '\x5b';
  RIGHT_BRACKET = '\x5d';
 
  initModel: DocumentInitializationModel;
  id: string;
  _type: DocumentType;
  name: string;
  description: string | undefined;
  uri: string;
  inspectionType: InspectionType;
  inspectionParameters: { [key: string]: string };
  inspectionSource: string;
  inspectionResult: string;
  isSource: boolean;
  isPropertyOrConstant: boolean;
  selectedRoot: string;
  classPath: string;
  initialized = false;
  errorOccurred = false;
  fields: Field[] = [];
  allFields: Field[] = [];
  terminalFields: Field[] = [];
  complexFieldsByClassIdentifier: { [key: string]: Field } = {};
  enumFieldsByClassIdentifier: { [key: string]: Field } = {};
  fieldsByPath: { [key: string]: Field } = {};
  fieldPaths: string[] = [];
  showFields = true;
  visibleInCurrentDocumentSearch = true;
  namespaces: NamespaceModel[] = [];
  characterEncoding: string;
  locale: string;
 
  set type(type: DocumentType) {
    this._type = type;
    this.isPropertyOrConstant =
      type === DocumentType.CONSTANT || type === DocumentType.PROPERTY;
  }
 
  get type(): DocumentType {
    return this._type;
  }
 
  getComplexField(classIdentifier: string): Field {
    return this.complexFieldsByClassIdentifier[classIdentifier];
  }
 
  getEnumField(classIdentifier: string): Field {
    return this.enumFieldsByClassIdentifier[classIdentifier];
  }
 
  getAllFields(): Field[] {
    return [...this.allFields];
  }
 
  /**
   * Return true if the specified field name already exists in the specified document definition,
   * false otherwise.
   *
   * @param targetField
   * @param targetFieldDocDefType
   */
  fieldExists(
    targetField: Field,
    targetFieldDocDefType: DocumentType
  ): boolean {
    for (const field of this.getAllFields()) {
      if (
        field.name === targetField.name &&
        field.docDef.type === targetFieldDocDefType
      ) {
        return true;
      }
    }
    return false;
  }
 
  isFieldsExist(fields: Field[]): boolean {
    if (fields == null || fields.length === 0) {
      return true;
    }
    const foundFields: Field[] = this.getFields(Field.getFieldPaths(fields));
    return foundFields != null && fields.length === foundFields.length;
  }
 
  getFields(fieldPaths: string[]): Field[] {
    const fields: Field[] = [];
    for (const fieldPath of fieldPaths) {
      const field = this.getField(fieldPath);
      if (field != null) {
        fields.push(field);
      }
    }
    return fields;
  }
 
  getName(showTypes: boolean): string {
    let name = this.name;
    if (showTypes && !this.isPropertyOrConstant) {
      const type = this.type;
      Eif (type) {
        name += ' (' + type + ')';
      }
    }
    return name;
  }
 
  getNamespaceForAlias(alias: string): NamespaceModel {
    // TODO: check this non null operator
    return this.namespaces.find((ns) => alias === ns.alias)!;
  }
 
  getField(fieldPath: string): Field | null {
    Iif (!fieldPath) {
      return null;
    }
    let field: Field = this.fieldsByPath[fieldPath];
    // if we can't find the field we're looking for, find parent fields and populate their children
    const pathSeparator: string = FIELD_PATH_SEPARATOR;
    let originalPath: string = fieldPath;
    // strip beginning path separator from path
    Eif (originalPath != null && originalPath.indexOf(pathSeparator) === 0) {
      originalPath = originalPath.substring(1);
    }
    if (field == null && originalPath.indexOf(pathSeparator) !== -1) {
      let currentParentPath = '';
      while (originalPath.indexOf(pathSeparator) !== -1) {
        const currentPathSection: string = originalPath.substr(
          0,
          originalPath.indexOf(pathSeparator)
        );
        currentParentPath += pathSeparator + currentPathSection;
        const parentField: Field = this.fieldsByPath[currentParentPath];
        Eif (parentField == null) {
          Eif (originalPath.indexOf(pathSeparator) !== -1) {
            originalPath = originalPath.substr(
              originalPath.indexOf(pathSeparator) + 1
            );
            continue;
          } else {
            break;
          }
          // https://github.com/atlasmap/atlasmap/issues/1128
          // throw new Error('Could not populate parent field with path \''
          //  + currentParentPath + '\' (for: ' + fieldPath + ')');
        }
        this.populateChildren(parentField);
        if (originalPath.indexOf(pathSeparator) !== -1) {
          originalPath = originalPath.substr(
            originalPath.indexOf(pathSeparator) + 1
          );
        }
      }
      field = this.fieldsByPath[fieldPath];
    }
    return field;
  }
 
  getComplexFields(): Field[] {
    return this.discoverAllComplexFields(this.fields);
  }
 
  getTerminalFields(): Field[] {
    return [...this.terminalFields];
  }
 
  initializeFromFields(): void {
    if (this.type === DocumentType.JAVA) {
      this.prepareComplexFields();
    }
 
    Field.alphabetizeFields(this.fields);
 
    for (const field of this.fields) {
      this.populateFieldData(field);
      this.allFields.push(field);
      this.populateChildren(field);
    }
 
    this.fieldPaths.sort();
    this.initialized = true;
  }
 
  updateField(field: Field, oldPath: string | null): void {
    Field.alphabetizeFields(this.fields);
    if (
      oldPath != null &&
      oldPath.length > 0 &&
      this.fieldsByPath[oldPath] != null
    ) {
      delete this.fieldsByPath[oldPath];
      CommonUtil.removeItemFromArray(oldPath, this.fieldPaths);
    } else {
      CommonUtil.removeItemFromArray(field.path, this.fieldPaths);
    }
    this.populateFieldData(field);
    this.fieldPaths.sort();
  }
 
  addField(field: Field): void {
    if (!field.parentField || this.isPropertyOrConstant) {
      this.fields.push(field);
      Field.alphabetizeFields(this.fields);
    } else {
      this.populateChildren(field.parentField);
      field.parentField.children.push(field);
      Field.alphabetizeFields(field.parentField.children);
    }
    this.populateFieldData(field);
    this.allFields.push(field);
    this.fieldPaths.sort();
  }
 
  /**
   * Return true if the passed field is terminal or children are detected, false otherwise.
   * @param field - target field
   */
  populateChildren(field: Field): boolean {
    // populate complex fields
    if (field.isTerminal() || field.children.length > 0) {
      return true;
    }
 
    let cachedField = this.getComplexField(field.classIdentifier);
    if (cachedField == null) {
      return false;
    }
 
    // copy cached field contents
    cachedField = cachedField.copy();
    for (let childField of cachedField.children) {
      childField = childField.copy();
      childField.parentField = field;
      this.rewriteFieldPath(childField);
      this.populateFieldData(childField);
      field.children.push(childField);
    }
 
    if (field.children.length > 0) {
      this.fieldPaths.sort();
      return true;
    } else {
      return false;
    }
  }
 
  private rewriteFieldPath(field: Field) {
    const parent = field.parentField;
    const pathSegments = field.path.split(FIELD_PATH_SEPARATOR);
    field.path = parent.path + FIELD_PATH_SEPARATOR + pathSegments.slice(-1)[0];
    for (let child of field.children) {
      this.rewriteFieldPath(child);
    }
  }
 
  /**
   * Clear all fields in this document.
   */
  clearFields(): void {
    this.initialized = false;
    this.fields = [];
    this.allFields = [];
    this.terminalFields = [];
    this.fieldPaths = [];
    this.namespaces = [];
    this.fieldsByPath = {};
    this.complexFieldsByClassIdentifier = {};
    this.enumFieldsByClassIdentifier = {};
  }
 
  getFieldIndex(field: Field, fields: Field[]): number {
    for (let i = 0; i < fields.length; i++) {
      Eif (fields[i].path === field.path) {
        return i;
      }
    }
    return -1;
  }
 
  /**
   * Remove the specified field from this document definition.
   *
   * @param field
   */
  removeField(field: Field): void {
    Iif (field == null) {
      return;
    }
    let targetIndex = this.getFieldIndex(field, this.fields);
    Eif (targetIndex > -1) {
      this.fields.splice(targetIndex, 1);
    }
    targetIndex = this.getFieldIndex(field, this.allFields);
    Eif (targetIndex > -1) {
      this.allFields.splice(targetIndex, 1);
    }
    targetIndex = this.getFieldIndex(field, this.terminalFields);
    Eif (targetIndex > -1) {
      this.terminalFields.splice(targetIndex, 1);
    }
    let oldFieldPath = field.path;
    CommonUtil.removeItemFromArray(oldFieldPath, this.fieldPaths);
    delete this.fieldsByPath[oldFieldPath];
    Iif (field.parentField != null) {
      CommonUtil.removeItemFromArray(field, field.parentField.children);
    }
  }
 
  updateFromMappings(mappingDefinition: MappingDefinition): void {
    if (mappingDefinition === null) {
      return;
    }
 
    for (const field of this.allFields) {
      field.partOfMapping = false;
      field.hasUnmappedChildren = false;
      field.partOfTransformation = false;
    }
 
    // FIXME: some of this work is happening N times for N source/target docs, should only happen once.
    for (const mapping of mappingDefinition.getAllMappings(true)) {
      for (const field of mapping.getAllFields()) {
        let parentField = field;
        // TODO: check this non null operator
        const partOfTransformation =
          mapping.getMappedFieldForField(field)!.actions.length > 0;
        while (parentField != null) {
          parentField.partOfMapping = true;
          parentField.partOfTransformation =
            parentField.partOfTransformation || partOfTransformation;
          parentField = parentField.parentField;
        }
      }
    }
    for (const field of this.allFields) {
      field.hasUnmappedChildren = Field.fieldHasUnmappedChild(field);
    }
  }
 
  private populateFieldData(field: Field): void {
    field.docDef = this;
    let newFieldKey = field.path;
    this.fieldPaths.push(newFieldKey);
    this.fieldsByPath[newFieldKey] = field;
 
    if (field.enumeration) {
      this.enumFieldsByClassIdentifier[field.classIdentifier] = field;
    }
    if (field.isTerminal()) {
      this.terminalFields.push(field);
    } else {
      for (const childField of field.children) {
        this.populateFieldData(childField);
        this.allFields.push(childField);
      }
    }
  }
 
  private prepareComplexFields(): void {
    const fields: Field[] = this.fields;
 
    // build complex field cache
    this.discoverComplexFields(fields);
 
    for (const key in this.complexFieldsByClassIdentifier) {
      Iif (!this.complexFieldsByClassIdentifier.hasOwnProperty(key)) {
        continue;
      }
      const cachedField: Field = this.complexFieldsByClassIdentifier[key];
      // remove children more than one level deep in cached fields
      for (const childField of cachedField.children) {
        childField.children = [];
      }
      // alphabetize complex field's childrein
      Field.alphabetizeFields(cachedField.children);
    }
  }
 
  private discoverAllComplexFields(fields: Field[]): Field[] {
    let complexFields: Field[] = [];
 
    for (const field of fields) {
      Iif (
        field.type === 'COMPLEX' &&
        (field.documentField.status === 'SUPPORTED' ||
          field.documentField.status === 'CACHED')
      ) {
        complexFields.push(field.copy());
      }
      Eif (field.children) {
        complexFields = complexFields.concat(
          this.discoverAllComplexFields(field.children)
        );
      }
    }
    return complexFields;
  }
 
  private discoverComplexFields(fields: Field[]): void {
    for (const field of fields) {
      if (field.type !== 'COMPLEX') {
        continue;
      }
      if (field.documentField.status === 'SUPPORTED') {
        this.complexFieldsByClassIdentifier[field.classIdentifier] =
          field.copy();
      }
      Eif (field.children) {
        this.discoverComplexFields(field.children);
      }
    }
  }
}