List of usage examples for javax.json JsonWriter close
@Override
void close();
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();/*from www. j a v a 2s . c om*/ 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 w w . ja v a2 s . c om */ 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()); }//from ww w. j a v a 2 s.c om } 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 w ww . ja v a2s. c o m * * @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: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/*from w ww . j a va 2 s . co 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
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); }/*from www. jav 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 saveTAData(AppDataComponent data, String filePath) throws IOException { TAData dataManager = (TAData) data;/*from www .j ava2s .c om*/ // 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); }//w ww .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 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 ww w . j a v a 2 s .co 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 w w.ja va 2 s.c o m } 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(); }