1   package org.daisy.pipeline.image.saxon.impl;
2   
3   import java.awt.image.BufferedImage;
4   import java.net.URL;
5   import java.net.URLDecoder;
6   
7   import javax.imageio.ImageIO;
8   
9   import net.sf.saxon.expr.XPathContext;
10  import net.sf.saxon.lib.ExtensionFunctionCall;
11  import net.sf.saxon.lib.ExtensionFunctionDefinition;
12  import net.sf.saxon.om.LazySequence;
13  import net.sf.saxon.om.Sequence;
14  import net.sf.saxon.om.StructuredQName;
15  import net.sf.saxon.trans.XPathException;
16  import net.sf.saxon.tree.iter.ArrayIterator;
17  import net.sf.saxon.value.BigIntegerValue;
18  import net.sf.saxon.value.IntegerValue;
19  import net.sf.saxon.value.SequenceType;
20  import net.sf.saxon.value.StringValue;
21  
22  import org.osgi.service.component.annotations.Component;
23  
24  import org.slf4j.Logger;
25  import org.slf4j.LoggerFactory;
26  
27  @Component(
28  	name = "pf:image-dimensions",
29  	service = { ExtensionFunctionDefinition.class }
30  )
31  @SuppressWarnings("serial")
32  public class ImageDimensions extends ExtensionFunctionDefinition {
33  
34  	private static final StructuredQName funcname = new StructuredQName("pf",
35  			"http://www.daisy.org/ns/pipeline/functions", "image-dimensions");
36  
37  	@Override
38  	public SequenceType[] getArgumentTypes() {
39  		return new SequenceType[] { SequenceType.SINGLE_STRING };
40  	}
41  
42  	public StructuredQName getFunctionQName() {
43  		return funcname;
44  	}
45  
46  	public SequenceType getResultType(SequenceType[] arg0) {
47  		return SequenceType.ATOMIC_SEQUENCE; // NUMERIC_SEQUENCE
48  	}
49  
50  	@Override
51  	public ExtensionFunctionCall makeCallExpression() {
52  		return new ExtensionFunctionCall() {
53  
54  			@Override
55  			public Sequence call(XPathContext context, Sequence[] arguments)
56  					throws XPathException {
57  				try {
58  					String path = ((StringValue) arguments[0])
59  							.getStringValue();
60  					BufferedImage image = ImageIO.read(new URL(URLDecoder
61  							.decode(path)));
62  					return new LazySequence(
63  							new ArrayIterator (new IntegerValue[] {
64  									new BigIntegerValue(image.getWidth()),
65  									new BigIntegerValue(image.getHeight()) }));
66  				} catch (Throwable e) {
67  					throw new XPathException("Unexpected error in pf:image-dimensions", e);
68  				}
69  			}
70  		};
71  	}
72  
73  	private static final Logger logger = LoggerFactory
74  			.getLogger(ImageDimensions.class);
75  }