Example usage for javax.json JsonArrayBuilder add

List of usage examples for javax.json JsonArrayBuilder add

Introduction

In this page you can find the example usage for javax.json JsonArrayBuilder add.

Prototype

JsonArrayBuilder add(JsonArrayBuilder builder);

Source Link

Document

Adds a JsonArray from an array builder to the array.

Usage

From source file:csg.files.CSGFiles.java

public void saveTAData(AppDataComponent data, String filePath) throws IOException {
    TAData dataManager = (TAData) data;/*from  ww  w.j  a  va2  s .  c o  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:com.seniorproject.semanticweb.services.WebServices.java

public String prepareResultWithCount(ArrayList<String> in) throws IOException {
    Multiset<String> multiset = HashMultiset.create();
    for (int i = 0; i < in.size(); i++) {
        if (in.get(i).length() > 0 && !in.get(i).equals("\"\"")) {
            multiset.add(in.get(i));/*from  ww  w  .jav a2 s .com*/
        }
    }
    JsonArrayBuilder out = Json.createArrayBuilder();
    JsonObjectBuilder resultObject = Json.createObjectBuilder();
    for (Multiset.Entry<String> entry : multiset.entrySet()) {
        List<String> matchList = new ArrayList<>();
        Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
        Matcher regexMatcher = regex.matcher(entry.getElement());
        while (regexMatcher.find()) {
            matchList.add(regexMatcher.group());
        }
        resultObject.add("elem", matchList.get(0));
        resultObject.add("count", entry.getCount());
        if (matchList.size() >= 2) {
            String label = "";
            for (int j = 1; j < matchList.size(); j++) {
                label += matchList.get(j);
            }
            resultObject.add("label", label);
        } else {
            resultObject.add("label", "");
        }
        out.add(resultObject);
    }

    return out.build().toString();
}

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));//  w w  w .ja va 2 s.c  o m
        }
    }

    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

@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 ww .  j a  va 2 s. com
    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:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

/**
 * Turn the shipments array into a JsonArray 
 * @return //from   w  w w.  j  a v  a 2 s.c  om
 */
private JsonArray shipmentsToJson() {
    final JsonArrayBuilder ab = Json.createArrayBuilder();

    if (shipments != null) {
        for (final ShipmentRec s : shipments) {
            ab.add(s.toJSON());
        }
    }

    return ab.build();

}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

/**
 * Turn the shipments array into a JsonArray 
 * @return /*w w  w  .  j  a v  a2 s  . co  m*/
 */
private JsonArray orderItemsToJson() {
    final JsonArrayBuilder ab = Json.createArrayBuilder();

    if (orderItems != null) {
        for (final OrderItemRec o : orderItems) {
            ab.add(o.toJSON());
        }
    }

    return ab.build();

}

From source file:org.kuali.student.ap.coursesearch.service.impl.CourseDetailsViewHelperServiceImpl.java

/**
 * @see org.kuali.student.ap.coursesearch.service.CourseDetailsViewHelperService#createFilterValidRegGroupsForRemovalEvent(String, String, String, java.util.List, javax.json.JsonObjectBuilder)
 *//*w  ww .  j  av a2 s  . com*/
@Override
public JsonObjectBuilder createFilterValidRegGroupsForRemovalEvent(String termId, String courseOfferingCode,
        String formatOfferingId, List<String> regGroupIds, JsonObjectBuilder eventList) {
    JsonObjectBuilder filterEvent = Json.createObjectBuilder();
    filterEvent.add("termId", termId.replace(".", "-"));
    filterEvent.add("courseOfferingCode", courseOfferingCode);
    filterEvent.add("formatOfferingId", formatOfferingId);

    // Deconstruct reg groups into list of AO and FO ids
    List<String> validActivities = new ArrayList<String>();
    for (String id : regGroupIds) {
        List<String> activityIds = new ArrayList<>();
        try {
            SearchRequestInfo request = new SearchRequestInfo(
                    CourseSearchConstants.KSAP_COURSE_SEARCH_AO_IDS_BY_OFFERED_REG_GROUP_ID_KEY);
            request.addParam(CourseSearchConstants.SearchParameters.REG_GROUP_ID, id);
            List<SearchResultRowInfo> rows = KsapFrameworkServiceLocator.getSearchService()
                    .search(request, KsapFrameworkServiceLocator.getContext().getContextInfo()).getRows();
            for (SearchResultRowInfo row : rows) {
                activityIds.add(KsapHelperUtil.getCellValue(row,
                        CourseSearchConstants.SearchResultColumns.ACTIVITY_OFFERING_ID));
            }
        } catch (InvalidParameterException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        } catch (MissingParameterException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        } catch (OperationFailedException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        } catch (PermissionDeniedException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        }
        if (activityIds != null && !activityIds.isEmpty()) {
            validActivities.addAll(activityIds);
        }
    }

    // Create json array of valid activity ids and add it to event
    JsonArrayBuilder activities = Json.createArrayBuilder();
    for (String activity : validActivities) {
        activities.add(activity);

    }
    filterEvent.add("activities", activities);

    eventList.add("FILTER_COURSE_OFFERING_FOR_REMOVAL", filterEvent);
    return eventList;
}

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);
    }// ww w . jav a 2s.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:org.kuali.student.ap.coursesearch.service.impl.CourseDetailsViewHelperServiceImpl.java

/**
 * @see org.kuali.student.ap.coursesearch.service.CourseDetailsViewHelperService#createFilterValidRegGroupsEvent
 *//*from ww w  . jav  a2 s  .c om*/
@Override
public JsonObjectBuilder createFilterValidRegGroupsEvent(String termId, String courseOfferingCode,
        String formatOfferingId, List<String> regGroups, JsonObjectBuilder eventList,
        Map<Object, Object> additionalRestrictions) {
    JsonObjectBuilder filterEvent = Json.createObjectBuilder();
    filterEvent.add("termId", termId.replace(".", "-"));
    filterEvent.add("courseOfferingCode", courseOfferingCode);
    filterEvent.add("formatOfferingId", formatOfferingId);

    // Deconstruct reg groups into list of AO and FO ids
    List<String> validFormatOfferings = new ArrayList<String>();
    List<String> validActivities = new ArrayList<String>();

    boolean singleRegGroupIdentified = false;
    for (String id : regGroups) {
        List<String> activityIds = new ArrayList<>();
        List<String> formatIds = new ArrayList<>();
        try {
            SearchRequestInfo request = new SearchRequestInfo(
                    CourseSearchConstants.KSAP_COURSE_SEARCH_AO_IDS_BY_OFFERED_REG_GROUP_ID_KEY);
            request.addParam(CourseSearchConstants.SearchParameters.REG_GROUP_ID, id);
            List<SearchResultRowInfo> rows = KsapFrameworkServiceLocator.getSearchService()
                    .search(request, KsapFrameworkServiceLocator.getContext().getContextInfo()).getRows();
            boolean hasSelectedActivities = false;
            for (SearchResultRowInfo row : rows) {
                String activityId = KsapHelperUtil.getCellValue(row,
                        CourseSearchConstants.SearchResultColumns.ACTIVITY_OFFERING_ID);
                activityIds.add(activityId);

                //Determine if any activities of a single reg group have been selected
                if (regGroups.size() == 1 && additionalRestrictions != null
                        && additionalRestrictions.get("selectedActivities") != null
                        && ((List<String>) additionalRestrictions.get("selectedActivities"))
                                .contains(activityId))
                    singleRegGroupIdentified = true;
            }

            request = new SearchRequestInfo(
                    CourseSearchConstants.KSAP_COURSE_SEARCH_FO_IDS_BY_OFFERED_REG_GROUP_ID_KEY);
            request.addParam(CourseSearchConstants.SearchParameters.REG_GROUP_ID, id);
            rows = KsapFrameworkServiceLocator.getSearchService()
                    .search(request, KsapFrameworkServiceLocator.getContext().getContextInfo()).getRows();
            for (SearchResultRowInfo row : rows) {
                formatIds.add(KsapHelperUtil.getCellValue(row,
                        CourseSearchConstants.SearchResultColumns.FORMAT_OFFERING_ID));
            }
        } catch (InvalidParameterException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        } catch (MissingParameterException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        } catch (OperationFailedException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        } catch (PermissionDeniedException e) {
            throw new IllegalArgumentException("Lui Service lookup error", e);
        }
        if (activityIds != null && !activityIds.isEmpty()) {
            validActivities.addAll(activityIds);
        }
        if (formatIds != null && !formatIds.isEmpty()) {
            validFormatOfferings.addAll(formatIds);
        }
    }

    //Send single regGroupId identified (i.e. selected) event
    if (singleRegGroupIdentified) {
        try {
            filterEvent.add("regGroupId", KSCollectionUtils.getRequiredZeroElement(regGroups));
        } catch (OperationFailedException e) {
            throw new IllegalArgumentException("Failure retrieving registration group", e);
        }
    } else {
        filterEvent.add("regGroupId", "");
    }

    // Create json array of valid activity ids and add it to event
    JsonArrayBuilder activities = Json.createArrayBuilder();
    for (String activity : validActivities) {
        activities.add(activity);

    }
    filterEvent.add("activities", activities);

    // Create json array of valid format ids and add it to event
    JsonArrayBuilder formats = Json.createArrayBuilder();
    for (String format : validFormatOfferings) {
        formats.add(format);

    }
    filterEvent.add("formatOfferings", formats);

    eventList.add("FILTER_COURSE_OFFERING", filterEvent);
    return eventList;
}

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);
    }/* w  w  w  . j  a  v  a 2 s  .co m*/
    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();
}