|
| 1 | +package com.dashjoin.jsonata.cli; |
| 2 | + |
| 3 | +import java.io.ByteArrayOutputStream; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.io.InputStreamReader; |
| 7 | +import java.io.UnsupportedEncodingException; |
| 8 | +import com.dashjoin.jsonata.json.Json; |
| 9 | + |
| 10 | +/** |
| 11 | + * Terminal utility functions + JSONata extensions. |
| 12 | + */ |
| 13 | +public class TerminalUtil { |
| 14 | + |
| 15 | + /** |
| 16 | + * Supported input formats from file/stdin |
| 17 | + */ |
| 18 | + public static enum InputFormat { |
| 19 | + /** |
| 20 | + * Automatically detect input format |
| 21 | + */ |
| 22 | + auto, |
| 23 | + /** |
| 24 | + * Input is in JSON format |
| 25 | + */ |
| 26 | + json, |
| 27 | + /** |
| 28 | + * Input is a text string |
| 29 | + */ |
| 30 | + string; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Reads the given input stream with the specified format. |
| 35 | + * |
| 36 | + * Note: reads the whole stream into memory (no "streaming mode" yet!) |
| 37 | + * |
| 38 | + * @param in |
| 39 | + * @param format |
| 40 | + * @return Input object |
| 41 | + * @throws IOException |
| 42 | + * @throws UnsupportedEncodingException |
| 43 | + */ |
| 44 | + public static Object readInput(InputStream in, InputFormat format) |
| 45 | + throws IOException, UnsupportedEncodingException { |
| 46 | + Object input = null; |
| 47 | + switch (format) { |
| 48 | + case auto: { |
| 49 | + if (in.markSupported()) |
| 50 | + in.mark(65536); |
| 51 | + try { |
| 52 | + // First try JSON, if there is an error, |
| 53 | + // reset the stream and use string format |
| 54 | + return readInput(in, InputFormat.json); |
| 55 | + } catch (Exception ex) { |
| 56 | + if (in.markSupported()) { |
| 57 | + in.reset(); |
| 58 | + return readInput(in, InputFormat.string); |
| 59 | + } |
| 60 | + // We cannot reset the stream: throw the exception |
| 61 | + // Need to specify the format manually in this case |
| 62 | + throw ex; |
| 63 | + } |
| 64 | + } |
| 65 | + case json: { |
| 66 | + input = Json.parseJson(new InputStreamReader(in)); |
| 67 | + break; |
| 68 | + } |
| 69 | + case string: { |
| 70 | + ByteArrayOutputStream result = new ByteArrayOutputStream(); |
| 71 | + byte[] buffer = new byte[1024]; |
| 72 | + for (int length; (length = in.read(buffer)) != -1;) { |
| 73 | + result.write(buffer, 0, length); |
| 74 | + } |
| 75 | + input = result.toString("UTF-8"); |
| 76 | + break; |
| 77 | + } |
| 78 | + default: |
| 79 | + throw new IllegalArgumentException("Unsupported input format: " + format); |
| 80 | + } |
| 81 | + return input; |
| 82 | + } |
| 83 | +} |
0 commit comments