1
0
mirror of https://github.com/mitb-archive/filebot synced 2024-08-13 17:03:45 -04:00
filebot/source/net/filebot/format/ExpressionFormatFunctions.java

75 lines
2.0 KiB
Java
Raw Normal View History

2014-04-19 02:30:29 -04:00
package net.filebot.format;
import static java.util.stream.Collectors.*;
import static net.filebot.util.FileUtilities.*;
2016-04-02 05:07:10 -04:00
import static net.filebot.util.RegularExpressions.*;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
2016-04-02 05:07:10 -04:00
import java.util.regex.Pattern;
import java.util.stream.Stream;
2016-03-27 09:52:59 -04:00
import groovy.lang.Closure;
/**
* Global functions available in the {@link ExpressionFormat}
*/
public class ExpressionFormatFunctions {
/**
* General helpers and utilities
*/
public static Object call(Object object) {
if (object instanceof Closure<?>) {
try {
return ((Closure<?>) object).call();
} catch (Exception e) {
return null;
}
}
if (object instanceof CharSequence && object.toString().isEmpty()) {
return null;
}
return object;
}
public static Object any(Object c1, Object c2, Object... cN) {
2016-03-31 15:58:24 -04:00
return stream(c1, c2, cN).findFirst().orElse(null);
}
2014-04-15 10:29:13 -04:00
public static List<Object> allOf(Object c1, Object c2, Object... cN) {
return stream(c1, c2, cN).collect(toList());
}
public static String concat(Object c1, Object c2, Object... cN) {
return stream(c1, c2, cN).map(Objects::toString).collect(joining());
}
protected static Stream<Object> stream(Object c1, Object c2, Object... cN) {
return Stream.concat(Stream.of(c1, c2), Stream.of(cN)).map(ExpressionFormatFunctions::call).filter(Objects::nonNull);
2014-04-15 10:29:13 -04:00
}
public static Map<String, String> csv(String path) throws IOException {
Map<String, String> map = new LinkedHashMap<String, String>();
streamLines(new File(path)).forEach(line -> {
2016-04-02 05:07:10 -04:00
for (Pattern delim : new Pattern[] { TAB, SEMICOLON }) {
String[] field = delim.split(line, 2);
2014-12-16 21:19:29 -05:00
if (field.length >= 2) {
map.put(field[0].trim(), field[1].trim());
2014-12-16 21:19:29 -05:00
break;
}
}
});
return map;
}
public static List<String> readLines(String path) throws IOException {
return streamLines(new File(path)).collect(toList());
}
}