001package net.filebot.format;
002
003import static java.util.Arrays.*;
004import static java.util.regex.Pattern.*;
005import static net.filebot.format.ExpressionFormatFunctions.*;
006import static net.filebot.similarity.ICU.*;
007import static net.filebot.similarity.Normalization.*;
008import static net.filebot.util.RegularExpressions.*;
009
010import java.io.File;
011import java.math.BigDecimal;
012import java.time.Instant;
013import java.time.LocalDateTime;
014import java.time.ZoneId;
015import java.time.temporal.Temporal;
016import java.time.temporal.TemporalAmount;
017import java.util.ArrayList;
018import java.util.Collection;
019import java.util.Date;
020import java.util.List;
021import java.util.Locale;
022import java.util.Map;
023import java.util.Map.Entry;
024import java.util.Objects;
025import java.util.TreeMap;
026import java.util.function.Function;
027import java.util.regex.Matcher;
028import java.util.regex.Pattern;
029import java.util.stream.Collectors;
030import java.util.stream.IntStream;
031import java.util.stream.Stream;
032
033import org.codehaus.groovy.runtime.DefaultGroovyMethods;
034import org.codehaus.groovy.runtime.StringGroovyMethods;
035import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
036
037import groovy.lang.Closure;
038
039import net.filebot.InvalidInputException;
040import net.filebot.media.MediaDetection;
041import net.filebot.util.DateTimeUtilities;
042import net.filebot.util.FileUtilities;
043import net.filebot.util.StringUtilities;
044
045public class ExpressionFormatMethods {
046
047        /**
048         * Convert all characters to lower case/
049         *
050         * e.g. "Firelfy" ➔ "firefly"
051         */
052        public static String lower(String self) {
053                return self.toLowerCase();
054        }
055
056        public static String lower(String self, String pattern) {
057                return StringUtilities.replaceAll(self, compile(pattern), (i, s) -> lower(s));
058        }
059
060        /**
061         * Convert all characters to upper case.
062         *
063         * e.g. "Firelfy" ➔ "FIREFLY"
064         */
065        public static String upper(String self) {
066                return self.toUpperCase();
067        }
068
069        public static String upper(String self, String pattern) {
070                return StringUtilities.replaceAll(self, compile(pattern), (i, s) -> upper(s));
071        }
072
073        /**
074         * Pad number patterns to length using the given character.
075         *
076         * e.g. "1x01" ➔ "01x001"
077         */
078        public static String pad(String self, int... length) {
079                if (length == null || length.length == 0) {
080                        throw new InvalidInputException("1 padding length is required");
081                }
082
083                return StringUtilities.replaceAll(self, DIGIT, (i, m) -> {
084                        return pad(m, length[i < length.length ? i : length.length - 1], "0");
085                });
086        }
087
088        public static String pad(Number self, int length) {
089                return pad(self.toString(), length, "0");
090        }
091
092        public static String pad(CharSequence self, int length, CharSequence padding) {
093                return StringGroovyMethods.padLeft(self, length, padding);
094        }
095
096        /**
097         * Round decimal number to precision.
098         *
099         * e.g. "3.14" ➔ "3.1"
100         */
101        public static Number round(Number self, int precision) {
102                return DefaultGroovyMethods.round(BigDecimal.valueOf(self.doubleValue()), precision);
103        }
104
105        /**
106         * Match pattern and return or unwind if pattern cannot be found.
107         */
108        public static String match(String self, String pattern) {
109                return match(self, pattern, -1);
110        }
111
112        public static String match(String self, String pattern, int matchGroup) {
113                Matcher matcher = compile(pattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS | MULTILINE).matcher(self);
114                if (matcher.find()) {
115                        return firstCapturingGroup(matcher, matchGroup);
116                }
117                throw new InvalidInputException("Pattern not found: " + pattern + ": " + self);
118        }
119
120        /**
121         * Match all occurrences of the given pattern or unwind if pattern cannot be found.
122         */
123        public static List<String> matchAll(String self, String pattern) {
124                return matchAll(self, pattern, -1);
125        }
126
127        public static List<String> matchAll(String self, String pattern, int matchGroup) {
128                List<String> matches = new ArrayList<String>();
129                Matcher matcher = compile(pattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS | MULTILINE).matcher(self);
130                while (matcher.find()) {
131                        matches.add(firstCapturingGroup(matcher, matchGroup));
132                }
133
134                if (matches.isEmpty()) {
135                        throw new InvalidInputException("Pattern not found: " + pattern + ": " + self);
136                }
137                return matches;
138        }
139
140        private static String firstCapturingGroup(Matcher self, int matchGroup) {
141                int g = matchGroup < 0 ? self.groupCount() > 0 ? 1 : 0 : matchGroup;
142
143                // return the entire match
144                if (g == 0) {
145                        return self.group();
146                }
147
148                // otherwise find first non-empty capturing group
149                return IntStream.rangeClosed(g, self.groupCount()).mapToObj(self::group).filter(Objects::nonNull).map(String::trim).filter(s -> s.length() > 0).findFirst().orElseThrow(() -> {
150                        return new InvalidInputException("Capturing group " + g + " not found");
151                });
152        }
153
154        public static String replaceAll(String self, String pattern) {
155                return compile(pattern).matcher(self).replaceAll("");
156        }
157
158        public static String removeAll(String self, String pattern) {
159                return compile(pattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS | MULTILINE).matcher(self).replaceAll("").trim();
160        }
161
162        /**
163         * Strip characters that aren't allowed on Windows from the given filename.
164         *
165         * e.g. "Sissi: The Young Empress" ➔ "Sissi The Young Empress"
166         */
167        public static String removeIllegalCharacters(String self) {
168                return FileUtilities.validateFileName(normalizeQuotationMarks(self));
169        }
170
171        /**
172         * Strip brackets and other clutter patterns.
173         * 
174         * e.g. [ONe]_Ano_Hana_01_(1280x720) ➔ Ano Hana 01
175         */
176        public static String clean(String self) {
177                return FileUtilities.validateFileName(MediaDetection.stripReleaseInfo(self, true));
178        }
179
180        /**
181         * Replace all spaces.
182         *
183         * e.g. "Doctor Who" ➔ "Doctor_Who"
184         */
185        public static String space(String self, String replacement) {
186                return normalizeSpace(self, replacement);
187        }
188
189        /**
190         * Replace all colons.
191         *
192         * e.g. "Sissi: The Young Empress" ➔ "Sissi - The Young Empress"
193         */
194        public static String colon(String self, String colon) {
195                return COLON.matcher(self).replaceAll(colon);
196        }
197
198        public static String colon(String self, String ratio, String colon) {
199                return COLON.matcher(RATIO.matcher(self).replaceAll(ratio)).replaceAll(colon);
200        }
201
202        /**
203         * Replace all slashes.
204         *
205         * e.g. "V_MPEG4/ISO/AVC" ➔ "V_MPEG4.ISO.AVC"
206         */
207        public static String slash(String self, String replacement) {
208                return SLASH.matcher(self).replaceAll(replacement);
209        }
210
211        /**
212         * Convert all initial characters to upper case.
213         *
214         * e.g. "The Day a new Demon was born" ➔ "The Day A New Demon Was Born"
215         */
216        public static String upperInitial(String self) {
217                return replaceHeadTail(self, String::toUpperCase, String::toString);
218        }
219
220        /**
221         * Convert all trailing characters to lower case.
222         *
223         * e.g. "Gundam SEED" ➔ "Gundam Seed"
224         */
225        public static String lowerTrail(String self) {
226                return replaceHeadTail(self, String::toString, String::toLowerCase);
227        }
228
229        private static String replaceHeadTail(String self, Function<String, String> head, Function<String, String> tail) {
230                Matcher matcher = compile("\\b((?<!['`´])\\p{Alnum}|['`´]\\p{Alnum}(?=\\p{Alnum}))(\\p{Alnum}*)\\b", UNICODE_CHARACTER_CLASS).matcher(self);
231
232                StringBuffer buffer = new StringBuffer();
233                while (matcher.find()) {
234                        matcher.appendReplacement(buffer, head.apply(matcher.group(1)) + tail.apply(matcher.group(2)));
235                }
236
237                return matcher.appendTail(buffer).toString();
238        }
239
240        /**
241         * Convert to sort name.
242         *
243         * e.g. "The Walking Dead" ➔ "Walking Dead"
244         */
245        public static String sortName(String self) {
246                return sortName(self, "$2");
247        }
248
249        public static String sortName(String self, String replacement) {
250                return compile("^(The|A|An)\\s(.+)", CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self).replaceFirst(replacement).trim();
251        }
252
253        public static String sortInitial(String self) {
254                // use primary initial, ignore The XY, A XY, etc
255                return sortName(self).codePoints().mapToObj(c -> {
256                        if (Character.isDigit(c)) {
257                                return "0-9";
258                        }
259                        if (Character.isLetter(c)) {
260                                String character = new StringBuilder(2).appendCodePoint(c).toString();
261                                return ascii(character).substring(0, 1).toUpperCase();
262                        }
263                        return null;
264                }).filter(Objects::nonNull).findFirst().get();
265        }
266
267        /**
268         * Reduce first name to initials.
269         *
270         * e.g. "James Cameron" ➔ "J. Cameron"
271         */
272        public static String initialName(String self) {
273                String[] words = SPACE.split(self);
274                for (int i = 0; i < words.length - 1; i++) {
275                        words[i] = words[i].charAt(0) + ".";
276                }
277                return String.join(" ", words);
278        }
279
280        public static String truncate(String self, int limit) {
281                if (limit >= self.length())
282                        return self;
283
284                return self.substring(0, limit);
285        }
286
287        public static String truncate(String self, int hardLimit, String nonWordPattern) {
288                if (hardLimit >= self.length())
289                        return self;
290
291                int softLimit = 0;
292                Matcher matcher = compile(nonWordPattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self);
293                while (matcher.find()) {
294                        if (matcher.start() > hardLimit) {
295                                break;
296                        }
297                        softLimit = matcher.start();
298                }
299                return truncate(self, softLimit);
300        }
301
302        /**
303         * Match substring before the given pattern or return the original value.
304         */
305        public static String before(String self, String pattern) {
306                Matcher matcher = compile(pattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self);
307
308                // pattern was found, return leading substring, else return original value
309                return matcher.find() ? self.substring(0, matcher.start()).trim() : self;
310        }
311
312        /**
313         * Match substring before the given pattern or return the original value.
314         */
315        public static String after(String self, String pattern) {
316                Matcher matcher = compile(pattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self);
317
318                // pattern was found, return trailing substring, else return original value
319                return matcher.find() ? self.substring(matcher.end(), self.length()).trim() : self;
320        }
321
322        /**
323         * Find match in case-insensitive mode.
324         */
325        public static Matcher findMatch(String self, String pattern) {
326                if (pattern == null || pattern.isEmpty()) {
327                        return null;
328                }
329
330                return compile(pattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self);
331        }
332
333        /**
334         * Find match in between word boundaries in case-insensitive mode.
335         */
336        public static Matcher findWordMatch(String self, String pattern) {
337                if (pattern == null || pattern.isEmpty()) {
338                        return null;
339                }
340
341                return findMatch(self, "(?<!\\p{Alnum})(?:" + pattern + ")(?!\\p{Alnum})");
342        }
343
344        /**
345         * Match brackets pattern.
346         *
347         * e.g. "The IT Crowd (UK)" ➔ "UK"
348         */
349        public static List<String> matchBrackets(String self) {
350                return matchAll(self, "[\\(\\[\\{]([^\\(\\[\\{\\)\\]\\}]+)[\\)\\]\\}]", 1);
351        }
352
353        /**
354         * Strip trailing parenthesis.
355         *
356         * e.g. "The IT Crowd (UK)" ➔ "The IT Crowd"
357         */
358        public static String replaceTrailingBrackets(String self) {
359                return replaceTrailingBrackets(self, "");
360        }
361
362        /**
363         * Replace trailing parenthesis.
364         *
365         * e.g. "The IT Crowd (UK)" ➔ "The IT Crowd [UK]"
366         */
367        public static String replaceTrailingBrackets(String self, String replacement) {
368                return compile("\\s*[(]([^)]*)[)]$", UNICODE_CHARACTER_CLASS).matcher(self).replaceAll(replacement);
369        }
370
371        /**
372         * Strip trailing part number.
373         *
374         * e.g. "Today Is the Day (1)" ➔ "Today Is the Day"
375         */
376        public static String replacePart(String self) {
377                return replacePart(self, "");
378        }
379
380        /**
381         * Replace trailing part number.
382         *
383         * e.g. "Today Is the Day (1)" ➔ "Today Is the Day, Part 1"
384         */
385        public static String replacePart(String self, String replacement) {
386                // handle '(n)', '(Part n)' and ': Part n' like syntax
387                String[] patterns = new String[] { "\\s*[(](\\w{1,3})[)]$", "\\W+Part (\\w+)\\W*$" };
388
389                for (String pattern : patterns) {
390                        Matcher matcher = compile(pattern, CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS).matcher(self);
391                        if (matcher.find()) {
392                                return matcher.replaceAll(replacement).trim();
393                        }
394                }
395
396                // no pattern matches, nothing to replace
397                return self;
398        }
399
400        /**
401         * Convert to acronym.
402         *
403         * e.g. "Deep Space 9" ➔ "DS9"
404         */
405        public static String acronym(String self) {
406                return compile("\\s|\\B\\p{Alnum}+", UNICODE_CHARACTER_CLASS).matcher(space(self, " ")).replaceAll("");
407        }
408
409        /**
410         * Replace numbers 1..12 with Roman numerals.
411         *
412         * e.g. "Star Wars: Episode 4" ➔ "Star Wars: Episode IV"
413         */
414        public static String roman(String self) {
415                TreeMap<Integer, String> numerals = new TreeMap<Integer, String>();
416                numerals.put(10, "X");
417                numerals.put(9, "IX");
418                numerals.put(5, "V");
419                numerals.put(4, "IV");
420                numerals.put(1, "I");
421
422                StringBuffer s = new StringBuffer();
423                Matcher m = compile("\\b\\d+\\b").matcher(self);
424                while (m.find()) {
425                        int n = Integer.parseInt(m.group());
426                        m.appendReplacement(s, n >= 1 && n <= 12 ? roman(n, numerals) : m.group());
427                }
428                return m.appendTail(s).toString();
429        }
430
431        public static String roman(Integer n, TreeMap<Integer, String> numerals) {
432                int l = numerals.floorKey(n);
433                if (n == l) {
434                        return numerals.get(n);
435                }
436                return numerals.get(l) + roman(n - l, numerals);
437        }
438
439        /**
440         * Apply any ICU script transliteration.
441         *
442         * e.g. "中国" ➔ "zhōng guó"
443         * 
444         * @see http://userguide.icu-project.org/transforms/general
445         */
446        public static String transliterate(String self, String transformIdentifier) {
447                return getTransliterator(transformIdentifier).transform(self);
448        }
449
450        /**
451         * Convert Unicode characters to ASCII.
452         *
453         * e.g. "カタカナ" ➔ "katakana"
454         */
455        public static String ascii(String self) {
456                return ascii(self, " ");
457        }
458
459        public static String ascii(String self, String fallback) {
460                return ASCII.transform(asciiQuotes(self)).replaceAll("\\P{ASCII}+", fallback).trim();
461        }
462
463        public static String asciiQuotes(String self) {
464                return normalizeQuotationMarks(self);
465        }
466
467        public static boolean isLatin(String self) {
468                return LATIN.matcher(self).matches();
469        }
470
471        public static List<String> getGraphemeClusters(String self) {
472                return tokenizeGraphemeClusters(self);
473        }
474
475        /**
476         * Apply replacement mappings.
477         *
478         * e.g. replace(ä:'ae', ö:'oe', ü:'ue')
479         */
480        public static String replace(String self, Map<?, ?> replacer) {
481                for (Entry<?, ?> m : replacer.entrySet()) {
482                        for (Object key : DefaultGroovyMethods.flatten(asList(m.getKey()))) {
483                                Pattern pattern = key instanceof Pattern ? (Pattern) key : compile(quote(key.toString()));
484                                if (m.getValue() instanceof Closure) {
485                                        self = StringGroovyMethods.replaceAll(self, pattern, (Closure) m.getValue());
486                                } else {
487                                        self = StringGroovyMethods.replaceAll(self, pattern, m.getValue().toString());
488                                }
489                        }
490                }
491                return self;
492        }
493
494        /**
495         * Apply replacement mappings.
496         *
497         * e.g. replace('Directors Cut':'DC')
498         */
499        public static <T> Collection<T> replace(Collection<T> self, Map<T, T> replacer) {
500                return self.stream().map(v -> replacer.getOrDefault(v, v)).filter(Objects::nonNull).collect(Collectors.toList());
501        }
502
503        /**
504         * Find matching pattern and return mapped value.
505         * 
506         * e.g. az.match('[a-f]': '/volume1', '[g-x]': '/volume2') ?: '/volume3'
507         */
508        public static Object match(String self, Map<?, ?> matcher) {
509                for (Entry<?, ?> m : matcher.entrySet()) {
510                        Pattern p = m.getKey() instanceof Pattern ? (Pattern) m.getKey() : compile(m.getKey().toString(), CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS | MULTILINE);
511                        if (p.matcher(self).find()) {
512                                return m.getValue();
513                        }
514                }
515                return null;
516        }
517
518        public static Object match(Collection<?> self, Map<?, ?> matcher) {
519                for (Entry<?, ?> m : matcher.entrySet()) {
520                        Pattern p = m.getKey() instanceof Pattern ? (Pattern) m.getKey() : compile(m.getKey().toString(), CASE_INSENSITIVE | UNICODE_CHARACTER_CLASS | MULTILINE);
521                        for (Object o : self) {
522                                if (o != null) {
523                                        if (p.matcher(o.toString()).find()) {
524                                                return m.getValue();
525                                        }
526                                }
527                        }
528                }
529                return null;
530        }
531
532        public static String joining(Collection<?> self, String delimiter) {
533                return joining(self, delimiter, "", "");
534        }
535
536        public static String joining(Collection<?> self, String delimiter, String prefix, String suffix) {
537                String[] list = DefaultGroovyMethods.flatten(self).stream().filter(Objects::nonNull).map(Objects::toString).filter(s -> !s.isEmpty()).toArray(String[]::new);
538
539                if (list.length > 0) {
540                        return prefix + String.join(delimiter, list) + suffix;
541                }
542
543                throw new InvalidInputException("Collection did not yield any values: " + self);
544        }
545
546        public static String joiningDistinct(Collection<?> self, String delimiter, Closure<?>... mapper) {
547                return joiningDistinct(self, delimiter, "", "", mapper);
548        }
549
550        public static String joiningDistinct(Collection<?> self, String delimiter, String prefix, String suffix, Closure<?>... mapper) {
551                Stream<?> stream = DefaultGroovyMethods.flatten(self).stream().filter(Objects::nonNull);
552
553                // apply custom mappers if any
554                if (mapper.length > 0) {
555                        stream = stream.flatMap(v -> stream(mapper).map(m -> m.call(v)).filter(Objects::nonNull));
556                }
557
558                // sort unique
559                String[] list = stream.map(Objects::toString).filter(s -> !s.isEmpty()).distinct().toArray(String[]::new);
560                if (list.length > 0) {
561                        return prefix + String.join(delimiter, list) + suffix;
562                }
563
564                throw new InvalidInputException("Collection did not yield any values: " + self);
565        }
566
567        public static List<?> bounds(Iterable<?> self) {
568                return Stream.of(DefaultGroovyMethods.min(self), DefaultGroovyMethods.max(self)).filter(Objects::nonNull).distinct().collect(Collectors.toList());
569        }
570
571        /**
572         * Unwind if an object does not satisfy the given predicate.
573         *
574         * e.g. (0..9)*.check{it < 10}.sum()
575         */
576        public static Object check(Object self, Closure<?> c) {
577                if (DefaultTypeTransformation.castToBoolean(c.call(self))) {
578                        return self;
579                }
580                throw new InvalidInputException("Object failed check: " + self);
581        }
582
583        /**
584         * Add values to the file name, after the file name, but before the subtitle language suffix and file extension.
585         *
586         * e.g. "Avatar (2009).mp4" ➔ "Avatar (2009) [720p].mp4"
587         */
588        public static StructuredFile derive(StructuredFile self, Object tag, Object... tags) {
589                return self.tag(component(null, tag, tags));
590        }
591
592        /**
593         * Add a value to the movie / series folder name.
594         * 
595         * e.g. Avatar (2009)/Avatar (2009) ➔ Avatar (2009) [TMDB-19995]/Avatar (2009)
596         */
597        public static StructuredFile deriveFolder(StructuredFile self, Object tag, Object... tags) {
598                return self.collection(component(null, tag, tags));
599        }
600
601        /**
602         * Add values to the file name, after the file name, but before the subtitle language suffix and file extension.
603         * 
604         * e.g. plex % {" by $director"} % {" [$vf, $vc, $ac]"}
605         */
606        public static StructuredFile mod(StructuredFile self, Object tag) {
607                return derive(self, tag);
608        }
609
610        /**
611         * Add a value to the movie / series folder name.
612         * 
613         * e.g. plex * " [TMDB-$id]"
614         */
615        public static StructuredFile multiply(StructuredFile self, Object tag) {
616                return deriveFolder(self, tag);
617        }
618
619        /**
620         * Add a value to the file name and the movie / series folder name.
621         * 
622         * e.g. plex ** " [TMDB-$id]"
623         */
624        public static StructuredFile power(StructuredFile self, Object tag) {
625                return deriveFolder(derive(self, tag), tag);
626        }
627
628        /**
629         * Nullify the Movies / TV Series folder level.
630         * 
631         * e.g. ~plex
632         */
633        public static StructuredFile bitwiseNegate(StructuredFile self) {
634                return self.category(null);
635        }
636
637        /**
638         * Add a value to the season folder level.
639         * 
640         * e.g. plex << { sy.bounds().joining('-', ' [', ']') }
641         */
642        public static StructuredFile leftShift(StructuredFile self, Object tag) {
643                return self.group(component(null, tag));
644        }
645
646        /**
647         * Add a value to the A-Z folder level.
648         * 
649         * e.g. plex >> { az }
650         */
651        public static StructuredFile rightShift(StructuredFile self, Object tag) {
652                return self.library(component(null, tag));
653        }
654
655        /**
656         * Replace subtitle language suffix.
657         * 
658         * e.g. plex ^ {'.'+lang.ISO2}
659         */
660        public static StructuredFile xor(StructuredFile self, Object tag) {
661                return self.suffix(null).suffix(component(null, tag));
662        }
663
664        /*
665         * File extensions
666         */
667
668        public static File ascii(File self) {
669                return SLASH.splitAsStream(self.getPath()).map(s -> {
670                        // Any-ASCII may introduce / into the file path (e.g. ½ => 1/2)
671                        return slash(ascii(s), " ");
672                }).collect(Collectors.collectingAndThen(Collectors.joining(File.separator), File::new));
673        }
674
675        public static long getDiskSpace(File self) {
676                return FileUtilities.getDiskSpace(self);
677        }
678
679        public static File getRoot(File self) {
680                return FileUtilities.listPath(self).get(0);
681        }
682
683        public static File getTail(File self) {
684                return FileUtilities.getRelativePathTail(self, FileUtilities.listPath(self).size() - 1);
685        }
686
687        public static List<File> listPath(File self) {
688                return FileUtilities.listPath(self);
689        }
690
691        public static List<File> listPath(File self, int tailSize) {
692                return FileUtilities.listPath(FileUtilities.getRelativePathTail(self, tailSize));
693        }
694
695        public static File getRelativePathTail(File self, int tailSize) {
696                return FileUtilities.getRelativePathTail(self, tailSize);
697        }
698
699        public static LocalDateTime toDate(Long self) {
700                return LocalDateTime.ofInstant(Instant.ofEpochMilli(self), ZoneId.systemDefault());
701        }
702
703        public static LocalDateTime toDate(Long self, String zone) {
704                return LocalDateTime.ofInstant(Instant.ofEpochMilli(self), ZoneId.of(zone, ZoneId.SHORT_IDS));
705        }
706
707        public static File toFile(String self) {
708                if (self == null || self.isEmpty()) {
709                        return null;
710                }
711                return new File(self);
712        }
713
714        public static File toFile(String self, String parent) {
715                if (self == null || self.isEmpty()) {
716                        return null;
717                }
718                File file = new File(self);
719                if (file.isAbsolute()) {
720                        return file;
721                }
722                return new File(parent, self);
723        }
724
725        public static Locale toLocale(String self) {
726                return Locale.forLanguageTag(self);
727        }
728
729        /*
730         * Date extensions
731         */
732
733        public static String format(Temporal self, String pattern) {
734                return format(self, pattern, Locale.US);
735        }
736
737        public static String format(Temporal self, String pattern, Locale locale) {
738                return DateTimeUtilities.format(self, pattern, locale);
739        }
740
741        public static String format(TemporalAmount self, String pattern) {
742                return format(self, pattern, Locale.US);
743        }
744
745        public static String format(TemporalAmount self, String pattern, Locale locale) {
746                return DateTimeUtilities.format(self, pattern, locale);
747        }
748
749        public static String format(Date self, String format) {
750                return format(self, format, Locale.US);
751        }
752
753        public static String format(Date self, String format, Locale locale) {
754                return DateTimeUtilities.format(self, format, locale);
755        }
756
757        public static Date parseDate(String self, String format) {
758                return parseDate(self, format, Locale.US);
759        }
760
761        public static Date parseDate(String self, String format, Locale locale) {
762                return DateTimeUtilities.toDate(DateTimeUtilities.parseDateTime(self, format, locale, ZoneId.systemDefault()));
763        }
764
765        public static Date parseDate(String self) {
766                return DateTimeUtilities.toDate(DateTimeUtilities.parseDateTime(self, ZoneId.systemDefault()));
767        }
768
769        public static int compareTo(Temporal self, String date) {
770                return DateTimeUtilities.toDateTime(self).toInstant().compareTo(DateTimeUtilities.parseDateTime(date, ZoneId.systemDefault()));
771        }
772
773        /*
774         * DSL extensions
775         */
776
777        public static File plus(File self, String path) {
778                return new File(self.getPath().concat(path));
779        }
780
781        public static File div(File self, String path) {
782                return new File(self, path);
783        }
784
785        public static File div(String self, String path) {
786                return new File(self, path);
787        }
788
789        public static File div(File self, File path) {
790                return new File(self, path.getPath());
791        }
792
793        public static File div(String self, File path) {
794                return new File(self, path.getPath());
795        }
796
797        public static File mod(File self, Object suffix) {
798                String name = FileUtilities.getNameWithoutExtension(self.getName());
799                String extension = self.getName().substring(name.length());
800
801                return new File(self.getParentFile(), component(null, name, suffix, extension));
802        }
803
804        public static String plus(String self, Closure closure) {
805                return concat(null, self, closure);
806        }
807
808        public static ReverseComparable negative(Comparable self) {
809                return new ReverseComparable(self);
810        }
811
812        private ExpressionFormatMethods() {
813                throw new UnsupportedOperationException();
814        }
815
816}