filebot/source/net/filebot/ui/rename/ExpressionFormatter.java

69 lines
1.7 KiB
Java
Raw Normal View History

2014-04-19 02:30:29 -04:00
package net.filebot.ui.rename;
import java.io.File;
import java.text.Format;
import java.util.Map;
import javax.script.ScriptException;
2014-04-19 02:30:29 -04:00
import net.filebot.format.ExpressionFormat;
import net.filebot.format.MediaBindingBean;
import net.filebot.similarity.Match;
class ExpressionFormatter implements MatchFormatter {
2015-07-25 18:47:19 -04:00
private final String expression;
private ExpressionFormat format;
2015-07-25 18:47:19 -04:00
private Format preview;
private Class<?> target;
2015-07-25 18:47:19 -04:00
public ExpressionFormatter(String expression, Format preview, Class<?> target) {
if (expression == null || expression.isEmpty())
throw new IllegalArgumentException("Expression must not be null or empty");
2015-07-25 18:47:19 -04:00
this.expression = expression;
this.preview = preview;
this.target = target;
2015-07-25 18:47:19 -04:00
}
2015-07-25 18:47:19 -04:00
@Override
public boolean canFormat(Match<?, ?> match) {
// target object is required, file is optional
return target.isInstance(match.getValue()) && (match.getCandidate() == null || match.getCandidate() instanceof File);
}
2015-07-25 18:47:19 -04:00
@Override
public String preview(Match<?, ?> match) {
return preview != null ? preview.format(match.getValue()) : match.getValue().toString();
}
2015-07-25 18:47:19 -04:00
@Override
public synchronized String format(Match<?, ?> match, Map<?, ?> context) throws ScriptException {
// lazy initialize script engine
if (format == null) {
format = new ExpressionFormat(expression);
}
2015-07-25 18:47:19 -04:00
// evaluate the expression using the given bindings
Object bindingBean = new MediaBindingBean(match.getValue(), (File) match.getCandidate(), (Map<File, Object>) context);
String result = format.format(bindingBean).trim();
2015-07-25 18:47:19 -04:00
// if result is empty, check for script exceptions
if (result.isEmpty() && format.caughtScriptException() != null) {
throw format.caughtScriptException();
}
2015-07-25 18:47:19 -04:00
return result;
}
2015-07-25 18:47:19 -04:00
}