List of usage examples for javax.json JsonWriter writeObject
void writeObject(JsonObject object);
From source file:Main.java
public static void main(String[] args) { JsonObject personObject = Json.createObjectBuilder().add("name", "Jack").add("age", 13) .add("isMarried", false) .add("address", Json.createObjectBuilder().add("street", "Main Street").add("city", "New York") .add("zipCode", "11111").build()) .add("phoneNumber", Json.createArrayBuilder().add("00-000-0000").add("11-111-1111").add("11-111-1112").build()) .build();/*ww w.jav a 2 s.c o m*/ StringWriter stringWriter = new StringWriter(); JsonWriter writer = Json.createWriter(stringWriter); writer.writeObject(personObject); writer.close(); System.out.println(stringWriter.getBuffer().toString()); }
From source file:com.amazon.alexa.avs.config.DeviceConfigUtils.java
/** * Writes the {@link DeviceConfig} back to disk. * * @param config//from w ww .j a va 2s . co 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:au.org.ands.vocabs.toolkit.provider.transform.SolrIndexTransformProvider.java
@Override public final boolean transform(final TaskInfo taskInfo, final JsonNode subtask, final HashMap<String, String> results) { Path dir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo)); ConceptHandler conceptHandler = new ConceptHandler(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path entry : stream) { RDFFormat format = Rio.getParserFormatForFileName(entry.toString()); RDFParser rdfParser = Rio.createParser(format); rdfParser.setRDFHandler(conceptHandler); FileInputStream is = new FileInputStream(entry.toString()); rdfParser.parse(is, entry.toString()); logger.debug("Reading RDF:" + entry.toString()); }/*w w w . j a v a2 s . co m*/ } catch (DirectoryIteratorException | IOException | RDFParseException | RDFHandlerException ex) { // I/O error encountered during the iteration, // the cause is an IOException results.put(TaskStatus.EXCEPTION, "Exception in SolrIndexTransform while Parsing RDF"); logger.error("Exception in SolrIndexTransform while Parsing RDF:", ex); return false; } String resultFileName = ToolkitFileUtils.getTaskOutputPath(taskInfo, "concepts_solr.json"); try { FileOutputStream out = new FileOutputStream(resultFileName); JsonObjectBuilder job = Json.createObjectBuilder(); job.add("concepts_count", conceptHandler.getCountedPrefLabels()); results.put("concepts_count", Integer.toString(conceptHandler.getCountedPrefLabels())); job.add("concepts_text", conceptHandler.getConceptText()); results.put("concepts_solr", resultFileName); JsonWriter jsonWriter = Json.createWriter(out); jsonWriter.writeObject(job.build()); jsonWriter.close(); } catch (FileNotFoundException ex) { results.put(TaskStatus.EXCEPTION, "Exception in SolrIndexTransform while generating result"); logger.error("Exception in SolrIndexTransform generating result:", ex); return false; } return true; }
From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java
/** * Enroll the user with member service//from www . java 2s . com * * @param req Enrollment request with the following fields: name, enrollmentSecret * @return enrollment */ public Enrollment enroll(EnrollmentRequest req) throws EnrollmentException { logger.debug(String.format("[MemberServicesFabricCAImpl.enroll] [%s]", req)); if (req == null) { throw new RuntimeException("req is not set"); } final String user = req.getEnrollmentID(); final String secret = req.getEnrollmentSecret(); if (StringUtil.isNullOrEmpty(user)) { throw new RuntimeException("req.enrollmentID is not set"); } if (StringUtil.isNullOrEmpty(secret)) { throw new RuntimeException("req.enrollmentSecret is not set"); } logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys..."); try { // generate ECDSA keys: signing and encryption keys KeyPair signingKeyPair = cryptoPrimitives.ecdsaKeyGen(); logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!"); // KeyPair encryptionKeyPair = cryptoPrimitives.ecdsaKeyGen(); PKCS10CertificationRequest csr = cryptoPrimitives.generateCertificationRequest(user, signingKeyPair); String pem = cryptoPrimitives.certificationRequestToPEM(csr); JsonObjectBuilder factory = Json.createObjectBuilder(); factory.add("certificate_request", pem); JsonObject postObject = factory.build(); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter)); jsonWriter.writeObject(postObject); jsonWriter.close(); String str = stringWriter.toString(); logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!"); String responseBody = httpPost(url + COP_ENROLLMENBASE, str, new UsernamePasswordCredentials(user, secret)); logger.debug("response" + responseBody); JsonReader reader = Json.createReader(new StringReader(responseBody)); JsonObject jsonst = (JsonObject) reader.read(); String result = jsonst.getString("result"); boolean success = jsonst.getBoolean("success"); logger.debug(String.format("[MemberServicesFabricCAImpl] enroll success:[%s], result:[%s]", success, result)); if (!success) { EnrollmentException e = new EnrollmentException("COP Failed response success is false. " + result, new Exception()); logger.error(e.getMessage()); throw e; } Base64.Decoder b64dec = Base64.getDecoder(); String signedPem = new String(b64dec.decode(result.getBytes())); logger.info(String.format("[MemberServicesFabricCAImpl] enroll returned pem:[%s]", signedPem)); Enrollment enrollment = new Enrollment(); enrollment.setKey(signingKeyPair); enrollment.setPublicKey(Hex.toHexString(signingKeyPair.getPublic().getEncoded())); enrollment.setCert(signedPem); return enrollment; } catch (Exception e) { EnrollmentException ee = new EnrollmentException(String.format("Failed to enroll user %s ", user), e); logger.error(ee.getMessage(), ee); throw ee; } }
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 . ja va 2 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 saveTAData(AppDataComponent data, String filePath) throws IOException { TAData dataManager = (TAData) data;//from ww w. 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 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); }/* ww w . j ava2 s . c o 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(); }
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);/*from www .j a va2s . c o m*/ } 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 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()); }//from w ww.j a va 2s . c om } 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: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 w w w. j a v a 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(); }