nl.dedicon.pipeline.braille.calabash.impl.EmptyBackCoverStep Maven / Gradle / Ivy
package nl.dedicon.pipeline.braille.calabash.impl;
import com.xmlcalabash.core.XProcException;
import com.xmlcalabash.core.XProcRuntime;
import com.xmlcalabash.core.XProcStep;
import com.xmlcalabash.io.ReadablePipe;
import com.xmlcalabash.io.WritablePipe;
import com.xmlcalabash.library.DefaultStep;
import com.xmlcalabash.runtime.XAtomicStep;
import java.io.InputStream;
import java.net.URL;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XQueryCompiler;
import net.sf.saxon.s9api.XQueryEvaluator;
import net.sf.saxon.s9api.XQueryExecutable;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmValue;
import nl.dedicon.pipeline.braille.step.Utils;
import org.daisy.common.xproc.calabash.XProcStepProvider;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
/**
* XProc step to make sure that the back cover of a volume has no braille
*
* @author Paul Rambags
*/
public class EmptyBackCoverStep extends DefaultStep {
private static final Logger logger = LoggerFactory.getLogger(EmptyBackCoverStep.class);
private static final QName _xquery = new QName("xquery");
private ReadablePipe source = null;
private WritablePipe result = null;
private EmptyBackCoverStep(XProcRuntime runtime, XAtomicStep step) {
super(runtime, step);
}
@Override
public void setInput(String port, ReadablePipe pipe) {
source = pipe;
}
@Override
public void setOutput(String port, WritablePipe pipe) {
result = pipe;
}
@Override
public void reset() {
source.resetReader();
result.resetWriter();
}
@Override
public void run() throws SaxonApiException {
super.run();
try {
XdmNode pef = source.read();
String xquery = getOption(_xquery, "");
// convert the immutable XdmNode to a modifiable Document
Document document = Utils.convertToDocument(pef);
InputStream query = new URL(xquery).openConnection().getInputStream();
XQueryCompiler xqCompiler = runtime.getProcessor().newXQueryCompiler();
XQueryExecutable xqExecutable = xqCompiler.compile(query);
XQueryEvaluator xqEvaluator = xqExecutable.load();
xqEvaluator.setSource(pef.asSource());
XdmValue xqResult = xqEvaluator.evaluate();
// get the first node from the result
XdmNode newPef = null;
for (XdmValue xqValue : xqResult) {
if (xqValue instanceof XdmNode) {
newPef = (XdmNode)xqValue;
break;
}
};
result.write(newPef);
} catch (Exception e) {
logger.error("dedicon:empty-back-cover failed", e);
throw new XProcException(step.getNode(), e);
}
}
@Component(
name = "dedicon:empty-back-cover",
service = {XProcStepProvider.class},
property = {"type:String={http://www.dedicon.nl}empty-back-cover"}
)
public static class Provider implements XProcStepProvider {
@Override
public XProcStep newStep(XProcRuntime runtime, XAtomicStep step) {
return new EmptyBackCoverStep(runtime, step);
}
}
}