filebot/source/net/filebot/format/ExpressionFormatFunctions.java

71 lines
1.8 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 java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
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;
}
}
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>();
for (String line : Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8)) {
2014-12-16 21:19:29 -05:00
for (String delim : new String[] { "\t", ";" }) {
String[] field = line.split(delim, 2);
if (field.length >= 2) {
map.put(field[0], field[1]);
break;
}
}
}
return map;
}
public static List<String> readLines(String path) throws IOException {
return Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
}
}