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