001/** 002 * Copyright (C) 2006-2025 Talend Inc. - www.talend.com 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.talend.sdk.component.api.record; 017 018import java.io.StringReader; 019import java.math.BigDecimal; 020import java.nio.charset.Charset; 021import java.nio.charset.CharsetEncoder; 022import java.nio.charset.StandardCharsets; 023import java.time.temporal.Temporal; 024import java.util.Arrays; 025import java.util.Base64; 026import java.util.Collection; 027import java.util.Comparator; 028import java.util.Date; 029import java.util.HashMap; 030import java.util.List; 031import java.util.Map; 032import java.util.Objects; 033import java.util.Optional; 034import java.util.concurrent.atomic.AtomicInteger; 035import java.util.function.BiConsumer; 036import java.util.function.Function; 037import java.util.stream.Collectors; 038import java.util.stream.Stream; 039 040import javax.json.Json; 041import javax.json.JsonValue; 042import javax.json.bind.annotation.JsonbTransient; 043import javax.json.stream.JsonParser; 044 045import lombok.EqualsAndHashCode; 046import lombok.RequiredArgsConstructor; 047import lombok.ToString; 048 049public interface Schema { 050 051 String SKIP_SANITIZE_PROPERTY = "talend.component.record.skip.sanitize"; 052 053 boolean SKIP_SANITIZE = Boolean.getBoolean(SKIP_SANITIZE_PROPERTY); 054 055 /** 056 * @return the type of this schema. 057 */ 058 Type getType(); 059 060 /** 061 * @return the nested element schema for arrays. 062 */ 063 Schema getElementSchema(); 064 065 /** 066 * @return the data entries for records (not contains meta data entries). 067 */ 068 List<Entry> getEntries(); 069 070 /** 071 * @return the metadata entries for records (not contains ordinary data entries). 072 */ 073 List<Entry> getMetadata(); 074 075 /** 076 * @return All entries, including data and metadata, of this schema. 077 */ 078 Stream<Entry> getAllEntries(); 079 080 default Map<String, Entry> getEntryMap() { 081 throw new UnsupportedOperationException("#getEntryMap is not implemented"); 082 } 083 084 /** 085 * Get a Builder from the current schema. 086 * 087 * @return a {@link Schema.Builder} 088 */ 089 default Schema.Builder toBuilder() { 090 throw new UnsupportedOperationException("#toBuilder is not implemented"); 091 } 092 093 /** 094 * Get all entries sorted by schema designed order. 095 * 096 * @return all entries ordered 097 */ 098 default List<Entry> getEntriesOrdered() { 099 return getEntriesOrdered(naturalOrder()); 100 } 101 102 /** 103 * Get all entries sorted using a custom comparator. 104 * 105 * @param comparator the comparator 106 * 107 * @return all entries ordered with provided comparator 108 */ 109 @JsonbTransient 110 default List<Entry> getEntriesOrdered(final Comparator<Entry> comparator) { 111 return getAllEntries().sorted(comparator).collect(Collectors.toList()); 112 } 113 114 /** 115 * Get the EntriesOrder defined with Builder. 116 * 117 * @return the EntriesOrder 118 */ 119 120 default EntriesOrder naturalOrder() { 121 throw new UnsupportedOperationException("#naturalOrder is not implemented"); 122 } 123 124 default Entry getEntry(final String name) { 125 return getEntryMap().get(name); 126 } 127 128 /** 129 * @return the metadata props 130 */ 131 Map<String, String> getProps(); 132 133 /** 134 * @param property : property name. 135 * 136 * @return the requested metadata prop 137 */ 138 String getProp(String property); 139 140 /** 141 * Get a property values from schema with its name. 142 * 143 * @param name : property's name. 144 * 145 * @return property's value. 146 */ 147 default JsonValue getJsonProp(final String name) { 148 final String prop = this.getProp(name); 149 if (prop == null) { 150 return null; 151 } 152 try (final StringReader reader = new StringReader(prop); 153 final JsonParser parser = Json.createParser(reader)) { 154 return parser.getValue(); 155 } catch (RuntimeException ex) { 156 return Json.createValue(prop); 157 } 158 } 159 160 enum Type { 161 162 RECORD(new Class<?>[] { Record.class }), 163 ARRAY(new Class<?>[] { Collection.class }), 164 STRING(new Class<?>[] { String.class, Object.class }), 165 BYTES(new Class<?>[] { byte[].class, Byte[].class }), 166 INT(new Class<?>[] { Integer.class }), 167 LONG(new Class<?>[] { Long.class }), 168 FLOAT(new Class<?>[] { Float.class }), 169 DOUBLE(new Class<?>[] { Double.class }), 170 BOOLEAN(new Class<?>[] { Boolean.class }), 171 DATETIME(new Class<?>[] { Long.class, Date.class, Temporal.class }), 172 DECIMAL(new Class<?>[] { BigDecimal.class }); 173 174 /** 175 * All compatibles Java classes 176 */ 177 private final Class<?>[] classes; 178 179 Type(final Class<?>[] classes) { 180 this.classes = classes; 181 } 182 183 /** 184 * Check if input can be affected to an entry of this type. 185 * 186 * @param input : object. 187 * 188 * @return true if input is null or ok. 189 */ 190 public boolean isCompatible(final Object input) { 191 if (input == null) { 192 return true; 193 } 194 for (final Class<?> clazz : classes) { 195 if (clazz.isInstance(input)) { 196 return true; 197 } 198 } 199 return false; 200 } 201 } 202 203 interface Entry { 204 205 /** 206 * @return The name of this entry. 207 */ 208 String getName(); 209 210 /** 211 * @return The raw name of this entry. 212 */ 213 String getRawName(); 214 215 /** 216 * @return the raw name of this entry if exists, else return name. 217 */ 218 String getOriginalFieldName(); 219 220 /** 221 * @return Type of the entry, this determine which other fields are populated. 222 */ 223 Type getType(); 224 225 /** 226 * @return Is this entry nullable or always valued. 227 */ 228 boolean isNullable(); 229 230 /** 231 * @return true if this entry is for metadata; false for ordinary data. 232 */ 233 boolean isMetadata(); 234 235 /** 236 * @param <T> the default value type. 237 * 238 * @return Default value for this entry. 239 */ 240 <T> T getDefaultValue(); 241 242 /** 243 * @return For type == record, the element type. 244 */ 245 Schema getElementSchema(); 246 247 /** 248 * @return Allows to associate to this field a comment - for doc purposes, no use in the runtime. 249 */ 250 String getComment(); 251 252 /** 253 * @return the metadata props 254 */ 255 Map<String, String> getProps(); 256 257 /** 258 * @param property : property name. 259 * 260 * @return the requested metadata prop 261 */ 262 String getProp(String property); 263 264 /** 265 * Get a property values from entry with its name. 266 * 267 * @param name : property's name. 268 * 269 * @return property's value. 270 */ 271 default JsonValue getJsonProp(final String name) { 272 final String prop = this.getProp(name); 273 if (prop == null) { 274 return null; 275 } 276 try (final StringReader reader = new StringReader(prop); 277 final JsonParser parser = Json.createParser(reader)) { 278 return parser.getValue(); 279 } catch (RuntimeException ex) { 280 return Json.createValue(prop); 281 } 282 } 283 284 /** 285 * 286 * @return the logical type property 287 */ 288 default String getLogicalType() { 289 return this.getProp(SchemaProperty.LOGICAL_TYPE); 290 } 291 292 /** 293 * @return an {@link Entry.Builder} from this entry. 294 */ 295 default Entry.Builder toBuilder() { 296 throw new UnsupportedOperationException("#toBuilder is not implemented"); 297 } 298 299 /** 300 * Plain builder matching {@link Entry} structure. 301 */ 302 interface Builder { 303 304 Builder withName(String name); 305 306 Builder withRawName(String rawName); 307 308 Builder withType(Type type); 309 310 default Builder withLogicalType(SchemaProperty.LogicalType logicalType) { 311 throw new UnsupportedOperationException("#withLogicalType is not implemented"); 312 } 313 314 default Builder withLogicalType(String logicalType) { 315 throw new UnsupportedOperationException("#withLogicalType is not implemented"); 316 } 317 318 Builder withNullable(boolean nullable); 319 320 Builder withMetadata(boolean metadata); 321 322 <T> Builder withDefaultValue(T value); 323 324 Builder withElementSchema(Schema schema); 325 326 Builder withComment(String comment); 327 328 Builder withProps(Map<String, String> props); 329 330 Builder withProp(String key, String value); 331 332 Entry build(); 333 } 334 } 335 336 /** 337 * Allows to build a {@link Schema}. 338 */ 339 interface Builder { 340 341 /** 342 * @param type schema type. 343 * 344 * @return this builder. 345 */ 346 Builder withType(Type type); 347 348 /** 349 * @param entry element for either an array or record type. 350 * 351 * @return this builder. 352 */ 353 Builder withEntry(Entry entry); 354 355 /** 356 * Insert the entry after the specified entry. 357 * 358 * @param after the entry name reference 359 * @param entry the entry name 360 * 361 * @return this builder 362 */ 363 default Builder withEntryAfter(String after, Entry entry) { 364 throw new UnsupportedOperationException("#withEntryAfter is not implemented"); 365 } 366 367 /** 368 * Insert the entry before the specified entry. 369 * 370 * @param before the entry name reference 371 * @param entry the entry name 372 * 373 * @return this builder 374 */ 375 default Builder withEntryBefore(String before, Entry entry) { 376 throw new UnsupportedOperationException("#withEntryBefore is not implemented"); 377 } 378 379 /** 380 * Remove entry from builder. 381 * 382 * @param name the entry name 383 * 384 * @return this builder 385 */ 386 default Builder remove(String name) { 387 throw new UnsupportedOperationException("#remove is not implemented"); 388 } 389 390 /** 391 * Remove entry from builder. 392 * 393 * @param entry the entry 394 * 395 * @return this builder 396 */ 397 default Builder remove(Entry entry) { 398 throw new UnsupportedOperationException("#remove is not implemented"); 399 } 400 401 /** 402 * Move an entry after another one. 403 * 404 * @param after the entry name reference 405 * @param name the entry name 406 */ 407 default Builder moveAfter(final String after, final String name) { 408 throw new UnsupportedOperationException("#moveAfter is not implemented"); 409 } 410 411 /** 412 * Move an entry before another one. 413 * 414 * @param before the entry name reference 415 * @param name the entry name 416 */ 417 default Builder moveBefore(final String before, final String name) { 418 throw new UnsupportedOperationException("#moveBefore is not implemented"); 419 } 420 421 /** 422 * Swap two entries. 423 * 424 * @param name the entry name 425 * @param with the other entry name 426 */ 427 default Builder swap(final String name, final String with) { 428 throw new UnsupportedOperationException("#swap is not implemented"); 429 } 430 431 /** 432 * @param schema nested element schema. 433 * 434 * @return this builder. 435 */ 436 Builder withElementSchema(Schema schema); 437 438 /** 439 * @param props schema properties 440 * 441 * @return this builder 442 */ 443 Builder withProps(Map<String, String> props); 444 445 /** 446 * @param key the prop key name 447 * @param value the prop value 448 * 449 * @return this builder 450 */ 451 Builder withProp(String key, String value); 452 453 /** 454 * @return the described schema. 455 */ 456 Schema build(); 457 458 /** 459 * Same as {@link Builder#build()} but entries order is specified by {@code order}. This takes precedence on any 460 * previous defined order with builder and may void it. 461 * 462 * @param order the wanted order for entries. 463 * @return the described schema. 464 */ 465 default Schema build(Comparator<Entry> order) { 466 throw new UnsupportedOperationException("#build(EntriesOrder) is not implemented"); 467 } 468 } 469 470 /** 471 * Sanitize name to be avro compatible. 472 * 473 * @param name : original name. 474 * 475 * @return avro compatible name. 476 */ 477 static String sanitizeConnectionName(final String name) { 478 if (SKIP_SANITIZE || name == null || name.isEmpty()) { 479 return name; 480 } 481 482 char current = name.charAt(0); 483 final CharsetEncoder ascii = Charset.forName(StandardCharsets.US_ASCII.name()).newEncoder(); 484 final boolean skipFirstChar = ((!ascii.canEncode(current)) || (!Character.isLetter(current) && current != '_')) 485 && name.length() > 1 && (!Character.isDigit(name.charAt(1))); 486 487 final StringBuilder sanitizedBuilder = new StringBuilder(); 488 489 if (!skipFirstChar) { 490 if (((!Character.isLetter(current)) && current != '_') || (!ascii.canEncode(current))) { 491 sanitizedBuilder.append('_'); 492 } else { 493 sanitizedBuilder.append(current); 494 } 495 } 496 for (int i = 1; i < name.length(); i++) { 497 current = name.charAt(i); 498 if (!ascii.canEncode(current)) { 499 if (Character.isLowerCase(current) || Character.isUpperCase(current)) { 500 sanitizedBuilder.append('_'); 501 } else { 502 final byte[] encoded = 503 Base64.getEncoder().encode(name.substring(i, i + 1).getBytes(StandardCharsets.UTF_8)); 504 final String enc = new String(encoded); 505 if (sanitizedBuilder.length() == 0 && Character.isDigit(enc.charAt(0))) { 506 sanitizedBuilder.append('_'); 507 } 508 for (int iter = 0; iter < enc.length(); iter++) { 509 if (Character.isLetterOrDigit(enc.charAt(iter))) { 510 sanitizedBuilder.append(enc.charAt(iter)); 511 } else { 512 sanitizedBuilder.append('_'); 513 } 514 } 515 } 516 } else if (Character.isLetterOrDigit(current)) { 517 sanitizedBuilder.append(current); 518 } else { 519 sanitizedBuilder.append('_'); 520 } 521 522 } 523 return sanitizedBuilder.toString(); 524 } 525 526 @RequiredArgsConstructor 527 @ToString 528 @EqualsAndHashCode 529 class EntriesOrder implements Comparator<Entry> { 530 531 private final OrderedMap<String> fieldsOrder; 532 533 // Keep comparator while no change occurs in fieldsOrder. 534 private Comparator<Entry> currentComparator = null; 535 536 /** 537 * Build an EntriesOrder according fields. 538 * 539 * @param fields the fields ordering. Each field should be {@code ,} separated. 540 * 541 * @return the order EntriesOrder 542 */ 543 public static EntriesOrder of(final String fields) { 544 return new EntriesOrder(fields); 545 } 546 547 /** 548 * Build an EntriesOrder according fields. 549 * 550 * @param fields the fields ordering. 551 * 552 * @return the order EntriesOrder 553 */ 554 public static EntriesOrder of(final Iterable<String> fields) { 555 final OrderedMap<String> orders = new OrderedMap<>(Function.identity(), fields); 556 return new EntriesOrder(orders); 557 } 558 559 public EntriesOrder(final String fields) { 560 if (fields == null || fields.isEmpty()) { 561 fieldsOrder = new OrderedMap<>(Function.identity()); 562 } else { 563 final List<String> fieldList = Arrays.stream(fields.split(",")).collect(Collectors.toList()); 564 fieldsOrder = new OrderedMap<>(Function.identity(), fieldList); 565 } 566 } 567 568 public EntriesOrder(final Iterable<String> fields) { 569 this(new OrderedMap<>(Function.identity(), fields)); 570 } 571 572 public Stream<String> getFieldsOrder() { 573 return this.fieldsOrder.streams(); 574 } 575 576 /** 577 * Move a field after another one. 578 * 579 * @param after the field name reference 580 * @param name the field name 581 * 582 * @return this EntriesOrder 583 */ 584 public EntriesOrder moveAfter(final String after, final String name) { 585 this.currentComparator = null; 586 this.fieldsOrder.moveAfter(after, name); 587 return this; 588 } 589 590 /** 591 * Move a field before another one. 592 * 593 * @param before the field name reference 594 * @param name the field name 595 * 596 * @return this EntriesOrder 597 */ 598 public EntriesOrder moveBefore(final String before, final String name) { 599 this.currentComparator = null; 600 this.fieldsOrder.moveBefore(before, name); 601 return this; 602 } 603 604 /** 605 * Swap two fields. 606 * 607 * @param name the field name 608 * @param with the other field 609 * 610 * @return this EntriesOrder 611 */ 612 public EntriesOrder swap(final String name, final String with) { 613 this.currentComparator = null; 614 this.fieldsOrder.swap(name, with); 615 return this; 616 } 617 618 public String toFields() { 619 return this.fieldsOrder.streams().collect(Collectors.joining(",")); 620 } 621 622 public Comparator<Entry> getComparator() { 623 if (this.currentComparator == null) { 624 final Map<String, Integer> entryPositions = new HashMap<>(); 625 final AtomicInteger index = new AtomicInteger(1); 626 this.fieldsOrder.streams() 627 .forEach( 628 (final String name) -> entryPositions.put(name, index.getAndIncrement())); 629 this.currentComparator = new EntryComparator(entryPositions); 630 } 631 return this.currentComparator; 632 } 633 634 @Override 635 public int compare(final Entry e1, final Entry e2) { 636 return this.getComparator().compare(e1, e2); 637 } 638 639 @RequiredArgsConstructor 640 static class EntryComparator implements Comparator<Entry> { 641 642 private final Map<String, Integer> entryPositions; 643 644 @Override 645 public int compare(final Entry e1, final Entry e2) { 646 final int index1 = this.entryPositions.getOrDefault(e1.getName(), Integer.MAX_VALUE); 647 final int index2 = this.entryPositions.getOrDefault(e2.getName(), Integer.MAX_VALUE); 648 if (index1 >= 0 && index2 >= 0) { 649 return index1 - index2; 650 } 651 if (index1 >= 0) { 652 return -1; 653 } 654 if (index2 >= 0) { 655 return 1; 656 } 657 return 0; 658 } 659 } 660 } 661 662 static Schema.Entry avoidCollision(final Schema.Entry newEntry, 663 final Function<String, Entry> entryGetter, 664 final BiConsumer<String, Entry> replaceFunction) { 665 if (SKIP_SANITIZE) { 666 return newEntry; 667 } 668 final Optional<Entry> collisionedEntry = Optional.ofNullable(entryGetter // 669 .apply(newEntry.getName())) // 670 .filter((final Entry field) -> !Objects.equals(field, newEntry)); 671 if (!collisionedEntry.isPresent()) { 672 // No collision, return new entry. 673 return newEntry; 674 } 675 final Entry matchedEntry = collisionedEntry.get(); 676 final boolean matchedToChange = matchedEntry.getRawName() != null && !(matchedEntry.getRawName().isEmpty()); 677 if (matchedToChange) { 678 // the rename has to be applied on entry already inside schema, so replace. 679 replaceFunction.accept(matchedEntry.getName(), newEntry); 680 } else if (newEntry.getRawName() == null || newEntry.getRawName().isEmpty()) { 681 // try to add exactly same raw, skip the add here. 682 return null; 683 } 684 final Entry fieldToChange = matchedToChange ? matchedEntry : newEntry; 685 int indexForAnticollision = 1; 686 final String baseName = Schema.sanitizeConnectionName(fieldToChange.getRawName()); // recalc primiti name. 687 688 String newName = baseName + "_" + indexForAnticollision; 689 while (entryGetter.apply(newName) != null) { 690 indexForAnticollision++; 691 newName = baseName + "_" + indexForAnticollision; 692 } 693 final Entry newFieldToAdd = fieldToChange.toBuilder().withName(newName).build(); 694 695 return newFieldToAdd; // matchedToChange ? newFieldToAdd : newEntry; 696 } 697}