| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package net.sf.saxon.resource; |
| 9 |
|
| 10 |
import net.sf.saxon.Configuration; |
| 11 |
import net.sf.saxon.expr.XPathContext; |
| 12 |
import net.sf.saxon.lib.Resource; |
| 13 |
import net.sf.saxon.lib.ResourceFactory; |
| 14 |
import net.sf.saxon.ma.json.ParseJsonFn; |
| 15 |
import net.sf.saxon.om.Item; |
| 16 |
import net.sf.saxon.om.Sequence; |
| 17 |
import net.sf.saxon.trans.XPathException; |
| 18 |
import net.sf.saxon.value.BooleanValue; |
| 19 |
import net.sf.saxon.value.StringValue; |
| 20 |
|
| 21 |
import java.io.IOException; |
| 22 |
import java.io.InputStream; |
| 23 |
import java.util.HashMap; |
| 24 |
import java.util.Map; |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
public class JSONResource implements Resource { |
| 31 |
private String href; |
| 32 |
private String jsonStr; |
| 33 |
private InputStream inputStream; |
| 34 |
private String encoding; |
| 35 |
|
| 36 |
public final static ResourceFactory FACTORY = new ResourceFactory() { |
| 37 |
public Resource makeResource(Configuration config, String resourceURI, String contentType, AbstractResourceCollection.InputDetails details) throws XPathException { |
| 38 |
return new JSONResource(resourceURI, details); |
| 39 |
} |
| 40 |
}; |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
public JSONResource(String href, AbstractResourceCollection.InputDetails details) { |
| 49 |
this.href = href; |
| 50 |
this.inputStream = details.inputStream; |
| 51 |
this.encoding = details.encoding; |
| 52 |
if (encoding == null) { |
| 53 |
encoding = "UTF-8"; |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public JSONResource(String href, InputStream in) { |
| 65 |
this.href = href; |
| 66 |
this.inputStream = in; |
| 67 |
this.encoding = "utf-8"; |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
public String getResourceURI() { |
| 72 |
return href; |
| 73 |
} |
| 74 |
|
| 75 |
public Item getItem(XPathContext context) throws XPathException { |
| 76 |
if (jsonStr == null) { |
| 77 |
try { |
| 78 |
StringBuilder sb = CatalogCollection.makeStringBuilderFromStream(inputStream, encoding); |
| 79 |
jsonStr = sb.toString(); |
| 80 |
} catch (IOException e) { |
| 81 |
throw new XPathException(e); |
| 82 |
} |
| 83 |
} |
| 84 |
Map<String, Sequence<?>> options = new HashMap<>(); |
| 85 |
options.put("liberal", BooleanValue.FALSE); |
| 86 |
options.put("duplicates", new StringValue("use-first")); |
| 87 |
options.put("escape", BooleanValue.FALSE); |
| 88 |
return ParseJsonFn.parse(jsonStr, options, context); |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
public String getContentType() { |
| 98 |
return "application/json"; |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
} |