Example usage for javax.json.stream JsonGenerator PRETTY_PRINTING

List of usage examples for javax.json.stream JsonGenerator PRETTY_PRINTING

Introduction

In this page you can find the example usage for javax.json.stream JsonGenerator PRETTY_PRINTING.

Prototype

String PRETTY_PRINTING

To view the source code for javax.json.stream JsonGenerator PRETTY_PRINTING.

Click Source Link

Document

Configuration property to generate JSON prettily.

Usage

From source file:com.amazon.alexa.avs.config.DeviceConfigUtils.java

/**
 * Writes the {@link DeviceConfig} back to disk.
 *
 * @param config//ww  w.  ja va2 s .c  o m
 */
public static void updateConfigFile(DeviceConfig config) {
    FileOutputStream file = null;
    try {
        file = new FileOutputStream(deviceConfigName);
        StringWriter stringWriter = new StringWriter();

        Map<String, Object> properties = new HashMap<String, Object>(1);
        properties.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
        JsonWriter jsonWriter = writerFactory.createWriter(stringWriter);
        jsonWriter.writeObject(config.toJson());
        jsonWriter.close();

        // We have to write to a separate StringWriter and trim() it because the pretty-printing
        // generator adds a newline at the beginning of the file.
        file.write(stringWriter.toString().trim().getBytes());
    } catch (FileNotFoundException e) {
        throw new RuntimeException("The required file " + deviceConfigName + " could not be updated.", e);
    } catch (IOException e) {
        throw new RuntimeException("The required file " + deviceConfigName + " could not be updated.", e);
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:de.pangaea.fixo3.xml.ProcessXmlFiles.java

private void run() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException,
        XPathExpressionException {
    // src/test/resources/, src/main/resources/files
    File folder = new File("src/main/resources/files");
    File[] files = folder.listFiles(new FileFilter() {

        @Override/*  w  w w .  j a  va2s. c o m*/
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith(".xml"))
                return true;

            return false;
        }
    });

    JsonArrayBuilder json = Json.createArrayBuilder();

    Document doc;
    String deviceLabel, deviceComment, deviceImage;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    final Map<String, String> prefixToNS = new HashMap<>();
    prefixToNS.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    prefixToNS.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    prefixToNS.put("sml", "http://www.opengis.net/sensorml/2.0");
    prefixToNS.put("gml", "http://www.opengis.net/gml/3.2");
    prefixToNS.put("gmd", "http://www.isotc211.org/2005/gmd");

    XPath x = XPathFactory.newInstance().newXPath();
    x.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            Objects.requireNonNull(prefix, "Namespace prefix cannot be null");
            final String uri = prefixToNS.get(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("Undeclared namespace prefix: " + prefix);
            }
            return uri;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException();
        }
    });

    XPathExpression exGmlName = x.compile("/sml:PhysicalSystem/gml:name");
    XPathExpression exGmlDescription = x.compile("/sml:PhysicalSystem/gml:description");
    XPathExpression exGmdUrl = x.compile(
            "/sml:PhysicalSystem/sml:documentation/sml:DocumentList/sml:document/gmd:CI_OnlineResource/gmd:linkage/gmd:URL");
    XPathExpression exTerm = x
            .compile("/sml:PhysicalSystem/sml:classification/sml:ClassifierList/sml:classifier/sml:Term");

    int m = 0;
    int n = 0;

    for (File file : files) {
        log.info(file.getName());
        doc = dbf.newDocumentBuilder().parse(new FileInputStream(file));

        deviceLabel = exGmlName.evaluate(doc).trim();
        deviceComment = exGmlDescription.evaluate(doc).trim();
        deviceImage = exGmdUrl.evaluate(doc).trim();
        NodeList terms = (NodeList) exTerm.evaluate(doc, XPathConstants.NODESET);

        JsonObjectBuilder jobDevice = Json.createObjectBuilder();

        jobDevice.add("name", toUri(deviceLabel));
        jobDevice.add("label", deviceLabel);
        jobDevice.add("comment", toAscii(deviceComment));
        jobDevice.add("image", deviceImage);

        JsonArrayBuilder jabSubClasses = Json.createArrayBuilder();

        for (int i = 0; i < terms.getLength(); i++) {
            Node term = terms.item(i);
            NodeList attributes = term.getChildNodes();

            String attributeLabel = null;
            String attributeValue = null;

            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                String attributeName = attribute.getNodeName();

                if (attributeName.equals("sml:label")) {
                    attributeLabel = attribute.getTextContent();
                } else if (attributeName.equals("sml:value")) {
                    attributeValue = attribute.getTextContent();
                }
            }

            if (attributeLabel == null || attributeValue == null) {
                throw new RuntimeException("Attribute label or value cannot be null [attributeLabel = "
                        + attributeLabel + "; attributeValue = " + attributeValue + "]");
            }

            if (attributeLabel.equals("model")) {
                continue;
            }

            if (attributeLabel.equals("manufacturer")) {
                jobDevice.add("manufacturer", attributeValue);
                continue;
            }

            n++;

            Quantity quantity = getQuantity(attributeValue);

            if (quantity == null) {
                continue;
            }

            m++;

            JsonObjectBuilder jobSubClass = Json.createObjectBuilder();
            JsonObjectBuilder jobCapability = Json.createObjectBuilder();
            JsonObjectBuilder jobQuantity = Json.createObjectBuilder();

            String quantityLabel = getQuantityLabel(attributeLabel);
            String capabilityLabel = deviceLabel + " " + quantityLabel;

            jobCapability.add("label", capabilityLabel);

            jobQuantity.add("label", quantity.getLabel());

            if (quantity.getValue() != null) {
                jobQuantity.add("value", quantity.getValue());
            } else if (quantity.getMinValue() != null && quantity.getMaxValue() != null) {
                jobQuantity.add("minValue", quantity.getMinValue());
                jobQuantity.add("maxValue", quantity.getMaxValue());
            } else {
                throw new RuntimeException(
                        "Failed to determine quantity value [attributeValue = " + attributeValue + "]");
            }

            jobQuantity.add("unitCode", quantity.getUnitCode());
            jobQuantity.add("type", toUri(quantityLabel));

            jobCapability.add("quantity", jobQuantity);
            jobSubClass.add("capability", jobCapability);

            jabSubClasses.add(jobSubClass);
        }

        jobDevice.add("subClasses", jabSubClasses);

        json.add(jobDevice);
    }

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);

    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(properties);
    JsonWriter jsonWriter = jsonWriterFactory.createWriter(new FileWriter(new File(jsonFileName)));
    jsonWriter.write(json.build());
    jsonWriter.close();

    System.out.println("Fraction of characteristics included: " + m + "/" + n);
}

From source file:csg.files.CSGFiles.java

@Override
public void saveData(AppDataComponent data, AppDataComponent recData, AppDataComponent schData,
        AppDataComponent projectData, AppDataComponent courseData, String filePath) throws IOException {
    // GET THE DATA
    TAData dataManager = (TAData) data;/*from  w  w  w  . j  a va  2 s.c  o  m*/
    CourseData cd = (CourseData) courseData;
    CSGWorkspace workspace = (CSGWorkspace) app.getWorkspaceComponent();

    if (workspace.getTitleTextField().getText().equals("")) {
        cd.setTitle("");
    } else {
        cd.setTitle(workspace.getTitleTextField().getText());
    }
    if (workspace.getInsNameTextField().getText().equals("")) {
        cd.setInsName("");
    } else {
        cd.setInsName(workspace.getInsNameTextField().getText());
    }
    if (workspace.getInsHomeTextField().getText().equals("")) {
        cd.setInsHome("");
    } else {
        cd.setInsHome(workspace.getInsHomeTextField().getText());
    }

    // NOW BUILD THE TA JSON OBJCTS TO SAVE
    JsonArrayBuilder taArrayBuilder = Json.createArrayBuilder();
    ObservableList<TeachingAssistant> tas = dataManager.getTeachingAssistants();
    for (TeachingAssistant ta : tas) {
        JsonObject taJson = Json.createObjectBuilder().add(JSON_NAME, ta.getName())
                .add(JSON_EMAIL, ta.getEmail()).add(JSON_UG, ta.isUndergrad().get()).build();
        taArrayBuilder.add(taJson);
    }
    JsonArray undergradTAsArray = taArrayBuilder.build();

    // NOW BUILD THE TIME SLOT JSON OBJCTS TO SAVE
    JsonArrayBuilder timeSlotArrayBuilder = Json.createArrayBuilder();
    ArrayList<TimeSlot> officeHours = TimeSlot.buildOfficeHoursList(dataManager);
    for (TimeSlot ts : officeHours) {
        JsonObject tsJson = Json.createObjectBuilder().add(JSON_DAY, ts.getDay()).add(JSON_TIME, ts.getTime())
                .add(JSON_NAME, ts.getName()).build();
        timeSlotArrayBuilder.add(tsJson);
    }
    JsonArray timeSlotsArray = timeSlotArrayBuilder.build();

    RecitationData recDataManager = (RecitationData) recData;
    JsonArrayBuilder recArrayBuilder = Json.createArrayBuilder();
    ObservableList<Recitation> recitations = recDataManager.getRecitations();

    for (Recitation recitation : recitations) {
        JsonObject recitationJson = Json.createObjectBuilder().add(JSON_SECTION, recitation.getSection())
                .add(JSON_INSTRUCTOR, recitation.getInstructor()).add(JSON_DAYTIME, recitation.getDayTime())
                .add(JSON_LOCATION, recitation.getLocation()).add(JSON_FIRSTTA, recitation.getFirstTA())
                .add(JSON_SECONDTA, recitation.getSecondTA()).build();
        recArrayBuilder.add(recitationJson);
    }
    JsonArray recitaitonArray = recArrayBuilder.build();

    ScheduleData schDataManager = (ScheduleData) schData;
    JsonArrayBuilder schArrayBuilder = Json.createArrayBuilder();
    ObservableList<ScheduleItem> schedule = schDataManager.getSchedule();

    for (ScheduleItem scheduleItem : schedule) {
        JsonObject scheduleJson = Json.createObjectBuilder().add(JSON_TYPE, scheduleItem.getType())
                .add(JSON_DAY, scheduleItem.getDate().getDayOfMonth())
                .add(JSON_MONTH, scheduleItem.getDate().getMonthValue())
                .add(JSON_YEAR, scheduleItem.getDate().getYear()).add(JSON_TIME, scheduleItem.getTime())
                .add(JSON_TITLE, scheduleItem.getTitle()).add(JSON_TOPIC, scheduleItem.getTopic())
                .add(JSON_LINK, scheduleItem.getLink()).add(JSON_CRITERIA, scheduleItem.getCriteria()).build();
        schArrayBuilder.add(scheduleJson);
    }
    JsonArray scheduleArray = schArrayBuilder.build();

    ProjectData projectDataManager = (ProjectData) projectData;
    JsonArrayBuilder teamArrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder studentArrayBuilder = Json.createArrayBuilder();
    ObservableList<Team> teams = projectDataManager.getTeams();
    ObservableList<Student> students = projectDataManager.getStudents();

    for (Team team : teams) {
        JsonObject teamsJson = Json.createObjectBuilder().add(JSON_NAME, team.getName())
                .add(JSON_COLOR, team.getColor()).add(JSON_TEXTCOLOR, team.getTextColor())
                .add(JSON_LINK, team.getLink()).build();
        teamArrayBuilder.add(teamsJson);
    }
    JsonArray teamArray = teamArrayBuilder.build();

    for (Student student : students) {
        JsonObject studentsJson = Json.createObjectBuilder().add(JSON_FIRSTNAME, student.getFirstName())
                .add(JSON_LASTNAME, student.getLastName()).add(JSON_TEAM, student.getTeam())
                .add(JSON_ROLE, student.getRole()).build();
        studentArrayBuilder.add(studentsJson);
    }
    JsonArray studentArray = studentArrayBuilder.build();

    CourseData courseDataManager = (CourseData) courseData;
    JsonArrayBuilder courseArrayBuilder = Json.createArrayBuilder();
    ObservableList<CourseTemplate> templates = courseDataManager.getTemplates();

    for (CourseTemplate template : templates) {
        JsonObject courseJson = Json.createObjectBuilder().add(JSON_USE, template.isUse().getValue())
                .add(JSON_NAVBAR, template.getNavbarTitle()).add(JSON_FILENAME, template.getFileName())
                .add(JSON_SCRIPT, template.getScript()).build();
        courseArrayBuilder.add(courseJson);
    }
    JsonArray courseArray = courseArrayBuilder.build();

    JsonObject courseJson = Json.createObjectBuilder().add(JSON_SUBJECT, courseDataManager.getSubject())
            .add(JSON_NUMBER, courseDataManager.getNumber()).add(JSON_SEMESTER, courseDataManager.getSemester())
            .add(JSON_YEAR, courseDataManager.getYear()).add(JSON_TITLE, courseDataManager.getTitle())
            .add(JSON_INSTRUCTORNAME, courseDataManager.getInsName())
            .add(JSON_INSTRUCTORHOME, courseDataManager.getInsHome())
            .add(JSON_BANNER, courseDataManager.getBannerLink())
            .add(JSON_LEFTFOOTER, courseDataManager.getLeftFooterLink())
            .add(JSON_RIGHTFOOTER, courseDataManager.getRightFooterLink())
            .add(JSON_EXPORTDIR, courseDataManager.getExportDir())
            .add(JSON_TEMPLATEDIR, courseDataManager.getTemplateDir())
            .add(JSON_STYLESHEET, courseDataManager.getStyleSheet()).build();

    // THEN PUT IT ALL RECITATIONS IN A JsonObject
    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_COURSE, courseJson)
            .add(JSON_COURSETEMPLATE, courseArray).add(JSON_START_HOUR, "" + dataManager.getStartHour())
            .add(JSON_END_HOUR, "" + dataManager.getEndHour()).add(JSON_UNDERGRAD_TAS, undergradTAsArray)
            .add(JSON_OFFICE_HOURS, timeSlotsArray).add(JSON_RECITATION, recitaitonArray)
            .add(JSON_STARTDAY, courseDataManager.getStartDay())
            .add(JSON_STARTMONTH, courseDataManager.getStartMonth())
            .add(JSON_STARTYEAR, courseDataManager.getStartYear())
            .add(JSON_ENDDAY, courseDataManager.getEndDay()).add(JSON_ENDMONTH, courseDataManager.getEndMonth())
            .add(JSON_ENDYEAR, courseDataManager.getEndYear()).add(JSON_SCHEDULEITEM, scheduleArray)
            .add(JSON_TEAMS, teamArray).add(JSON_STUDENTS, studentArray).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();

}

From source file:csg.files.CSGFiles.java

public void saveTAData(AppDataComponent data, String filePath) throws IOException {
    TAData dataManager = (TAData) data;//from  w  ww. j a v a  2  s  . co  m

    // NOW BUILD THE TA JSON OBJCTS TO SAVE
    JsonArrayBuilder taArrayBuilder = Json.createArrayBuilder();
    ObservableList<TeachingAssistant> tas = dataManager.getTeachingAssistants();
    for (TeachingAssistant ta : tas) {
        JsonObject taJson = Json.createObjectBuilder().add(JSON_NAME, ta.getName())
                .add(JSON_EMAIL, ta.getEmail()).add(JSON_UG, ta.isUndergrad().get()).build();
        taArrayBuilder.add(taJson);
    }
    JsonArray undergradTAsArray = taArrayBuilder.build();

    // NOW BUILD THE TIME SLOT JSON OBJCTS TO SAVE
    JsonArrayBuilder timeSlotArrayBuilder = Json.createArrayBuilder();
    ArrayList<TimeSlot> officeHours = TimeSlot.buildOfficeHoursList(dataManager);
    for (TimeSlot ts : officeHours) {
        JsonObject tsJson = Json.createObjectBuilder().add(JSON_DAY, ts.getDay()).add(JSON_TIME, ts.getTime())
                .add(JSON_NAME, ts.getName()).build();
        timeSlotArrayBuilder.add(tsJson);
    }
    JsonArray timeSlotsArray = timeSlotArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_START_HOUR, "" + dataManager.getStartHour())
            .add(JSON_END_HOUR, "" + dataManager.getEndHour()).add(JSON_UNDERGRAD_TAS, undergradTAsArray)
            .add(JSON_OFFICE_HOURS, timeSlotsArray).build();

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:csg.files.CSGFiles.java

public void saveRecitationData(AppDataComponent recData, String filePath) throws IOException {

    RecitationData recDataManager = (RecitationData) recData;
    JsonArrayBuilder recArrayBuilder = Json.createArrayBuilder();
    ObservableList<Recitation> recitations = recDataManager.getRecitations();

    for (Recitation recitation : recitations) {
        JsonObject recitationJson = Json.createObjectBuilder().add(JSON_SECTION, recitation.getSection())
                .add(JSON_INSTRUCTOR, recitation.getInstructor()).add(JSON_DAYTIME, recitation.getDayTime())
                .add(JSON_LOCATION, recitation.getLocation()).add(JSON_FIRSTTA, recitation.getFirstTA())
                .add(JSON_SECONDTA, recitation.getSecondTA()).build();
        recArrayBuilder.add(recitationJson);
    }// w  ww . j av a2 s .c o m
    JsonArray recitaitonArray = recArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_RECITATION, recitaitonArray).build();

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:csg.files.CSGFiles.java

public void saveScheduleData(AppDataComponent schData, String filePath) throws IOException {
    ScheduleData schDataManager = (ScheduleData) schData;
    JsonArrayBuilder schArrayBuilder = Json.createArrayBuilder();
    ObservableList<ScheduleItem> schedule = schDataManager.getSchedule();

    ArrayList<ScheduleItem> holidays = new ArrayList();
    ArrayList<ScheduleItem> lectures = new ArrayList();
    ArrayList<ScheduleItem> references = new ArrayList();
    ArrayList<ScheduleItem> recitations = new ArrayList();
    ArrayList<ScheduleItem> hws = new ArrayList();

    for (int i = 0; i < schedule.size(); i++) {
        if (schedule.get(i).getType().equals("holiday")) {
            holidays.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("lecture")) {
            lectures.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("reference")) {
            references.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("recitation")) {
            recitations.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("hw")) {
            hws.add(schedule.get(i));//from   ww  w. ja v a2s  . c  om
        }
    }

    JsonArrayBuilder holidayArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : holidays) {
        JsonObject holidayJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_LINK, scheduleItem.getLink()).build();
        holidayArrayBuilder.add(holidayJson);
    }
    JsonArray holidayArray = holidayArrayBuilder.build();

    JsonArrayBuilder lectureArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : lectures) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).add(JSON_LINK, scheduleItem.getLink()).build();
        lectureArrayBuilder.add(lecJson);
    }
    JsonArray lectureArray = lectureArrayBuilder.build();

    JsonArrayBuilder referencesArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : references) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).add(JSON_LINK, scheduleItem.getLink()).build();
        referencesArrayBuilder.add(lecJson);
    }
    JsonArray referenceArray = referencesArrayBuilder.build();

    JsonArrayBuilder recitationArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : recitations) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).build();
        recitationArrayBuilder.add(lecJson);
    }
    JsonArray recitaitonArray = recitationArrayBuilder.build();

    JsonArrayBuilder hwArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : hws) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).add(JSON_LINK, scheduleItem.getLink())
                .add(JSON_TIME, scheduleItem.getTime()).add(JSON_CRITERIA, scheduleItem.getCriteria()).build();
        hwArrayBuilder.add(lecJson);
    }
    JsonArray hwArray = hwArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_MONDAYMON, workspace.getMonMonthDate())
            .add(JSON_MONDAYDAY, workspace.getMonDayDate()).add(JSON_FRIDAYMONTH, workspace.getFriMonthDate())
            .add(JSON_FRIDAYDAY, workspace.getFriDayDate()).add(JSON_HOLIDAYS, holidayArray)
            .add(JSON_LECTURES, lectureArray).add(JSON_REF, referenceArray)
            .add(JSON_RECITATION, recitaitonArray).add(JSON_HW, hwArray).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:csg.files.CSGFiles.java

public void saveCourseData(AppDataComponent courseData, String filePath) throws IOException {
    CourseData courseDataManager = (CourseData) courseData;
    JsonArrayBuilder courseArrayBuilder = Json.createArrayBuilder();
    JsonArray courseArray = courseArrayBuilder.build();

    CSGWorkspace workspace = (CSGWorkspace) app.getWorkspaceComponent();
    JsonObject courseJson = Json.createObjectBuilder().add(JSON_SUBJECT, courseDataManager.getSubject())
            .add(JSON_NUMBER, courseDataManager.getNumber()).add(JSON_SEMESTER, courseDataManager.getSemester())
            .add(JSON_YEAR, courseDataManager.getYear()).add(JSON_TITLE, courseDataManager.getTitle())
            .add(JSON_INSTRUCTORNAME, courseDataManager.getInsName())
            .add(JSON_INSTRUCTORHOME, courseDataManager.getInsHome())
            .add(JSON_BANNER, courseDataManager.getBannerLink())
            .add(JSON_LEFTFOOTER, courseDataManager.getLeftFooterLink())
            .add(JSON_RIGHTFOOTER, courseDataManager.getRightFooterLink())
            .add(JSON_STYLESHEET, courseDataManager.getStyleSheet()).build();

    ObservableList<CourseTemplate> templates = courseDataManager.getTemplates();

    for (CourseTemplate template : templates) {
        JsonObject cJson = Json.createObjectBuilder().add(JSON_USE, template.isUse().getValue())
                .add(JSON_NAVBAR, template.getNavbarTitle()).add(JSON_FILENAME, template.getFileName())
                .add(JSON_SCRIPT, template.getScript()).build();
        courseArrayBuilder.add(cJson);/*  w  w  w.j a v a2  s.c om*/
    }
    courseArray = courseArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_COURSE, courseJson)
            .add(JSON_COURSETEMPLATE, courseArray).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:csg.files.CSGFiles.java

public void saveTeamsAndStudentsData(AppDataComponent projectData, String filePath) throws IOException {
    ProjectData projectDataManager = (ProjectData) projectData;
    JsonArrayBuilder teamArrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder studentArrayBuilder = Json.createArrayBuilder();
    ObservableList<Team> teams = projectDataManager.getTeams();
    ObservableList<Student> students = projectDataManager.getStudents();

    for (Team team : teams) {
        JsonObject teamsJson = Json.createObjectBuilder().add(JSON_NAME, team.getName())
                .add(JSON_RED, (Integer.parseInt(team.getColor().toString().substring(0, 2), 16)))
                .add(JSON_GREEN, (Integer.parseInt(team.getColor().toString().substring(2, 4), 16)))
                .add(JSON_BLUE, (Integer.parseInt(team.getColor().toString().substring(4, 6), 16)))
                .add(JSON_TEXTCOLOR, "#" + team.getTextColor()).build();
        teamArrayBuilder.add(teamsJson);
    }/*from   www  . j  av a2s.c om*/
    JsonArray teamArray = teamArrayBuilder.build();

    for (Student student : students) {
        JsonObject studentsJson = Json.createObjectBuilder().add(JSON_LASTNAME, student.getLastName())
                .add(JSON_FIRSTNAME, student.getFirstName()).add(JSON_TEAM, student.getTeam())
                .add(JSON_ROLE, student.getRole()).build();
        studentArrayBuilder.add(studentsJson);
    }
    JsonArray studentArray = studentArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_TEAMS, teamArray)
            .add(JSON_STUDENTS, studentArray).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:csg.files.CSGFiles.java

public void saveProjectsData(AppDataComponent courseData, AppDataComponent projectData, String filePath)
        throws IOException {

    CourseData courseDataManager = (CourseData) courseData;
    ProjectData projectDataManager = (ProjectData) projectData;

    ObservableList<Student> students = projectDataManager.getStudents();

    JsonArrayBuilder studentArrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder teamArrayBuilder = Json.createArrayBuilder();
    ObservableList<Team> teams = projectDataManager.getTeams();

    for (Team team : teams) {
        for (Student student : students) {
            if (student.getTeam().equals(team.getName())) {
                studentArrayBuilder.add(student.getFirstName() + " " + student.getLastName());
            }/* w  w w .  ja v  a  2  s  . com*/
        }
        JsonArray studentArray = studentArrayBuilder.build();
        JsonObject teamsJson = Json.createObjectBuilder().add(JSON_NAME, team.getName())
                .add(JSON_STUDENTS, studentArray).add(JSON_LINK, team.getLink()).build();
        teamArrayBuilder.add(teamsJson);
    }
    JsonArray teamArray = teamArrayBuilder.build();

    CSGWorkspace workspace = (CSGWorkspace) app.getWorkspaceComponent();
    JsonArrayBuilder courseJsonBuilder = Json.createArrayBuilder();
    JsonObject coursesJson = Json.createObjectBuilder()
            .add(JSON_SEMESTER, courseDataManager.getSemester() + " " + courseDataManager.getYear())
            .add(JSON_PROJECTS, teamArray).build();
    courseJsonBuilder.add(coursesJson);

    JsonArray courseJsonArr = courseJsonBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_WORK, courseJsonArr).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:org.dcm4che3.tool.dcm2json.Dcm2Json.java

private JsonGenerator createGenerator(OutputStream out) {
    Map<String, ?> conf = new HashMap<String, Object>(2);
    if (indent)//w w  w . j a  va 2 s .c o  m
        conf.put(JsonGenerator.PRETTY_PRINTING, null);
    return Json.createGeneratorFactory(conf).createGenerator(out);
}