Example usage for javax.json JsonReaderFactory createReader

List of usage examples for javax.json JsonReaderFactory createReader

Introduction

In this page you can find the example usage for javax.json JsonReaderFactory createReader.

Prototype

JsonReader createReader(InputStream in);

Source Link

Document

Creates a JSON reader from a byte stream.

Usage

From source file:org.apache.johnzon.maven.plugin.ExampleToModelMojo.java

private void generate(final JsonReaderFactory readerFactory, final File source, final Writer writer,
        final String javaName) throws MojoExecutionException {
    JsonReader reader = null;// w w w .  java  2s.  com
    try {
        reader = readerFactory.createReader(new FileReader(source));
        final JsonStructure structure = reader.read();
        if (JsonArray.class.isInstance(structure) || !JsonObject.class.isInstance(structure)) { // quite redundant for now but to avoid surprises in future
            throw new MojoExecutionException(
                    "This plugin doesn't support array generation, generate the model (generic) and handle arrays in your code");
        }

        final JsonObject object = JsonObject.class.cast(structure);
        final Collection<String> imports = new TreeSet<String>();

        // while we browse the example tree just store imports as well, avoids a 2 passes processing duplicating imports logic
        final StringWriter memBuffer = new StringWriter();
        generateFieldsAndMethods(memBuffer, object, "    ", imports);

        if (header != null) {
            writer.write(header);
            writer.write('\n');
        }

        writer.write("package " + packageBase + ";\n\n");

        if (!imports.isEmpty()) {
            for (final String imp : imports) {
                writer.write("import " + imp + ";\n");
            }
            writer.write('\n');
        }

        writer.write("public class " + javaName + " {\n");
        writer.write(memBuffer.toString());
        writer.write("}\n");
    } catch (final IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}