javax.json.stream.JsonGenerator Java Examples
The following examples show how to use
javax.json.stream.JsonGenerator.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonSecurityMessage.java From aceql-http with GNU Lesser General Public License v2.1 | 7 votes |
/** * Builds a security error message in JSON format for Statements * * @param sqlOrder * @param errorMessage * @param doPrettyPrinting * @return */ public static String statementNotAllowedBuild(String sqlOrder, String errorMessage, boolean doPrettyPrinting) { try { JsonGeneratorFactory jf = JsonUtil .getJsonGeneratorFactory(doPrettyPrinting); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator gen = jf.createGenerator(out); gen.writeStartObject(); gen.write(Tag.PRODUCT_SECURITY, errorMessage); gen.write("SQL order", sqlOrder); gen.writeEnd(); gen.close(); return out.toString("UTF-8"); } catch (Exception e) { String returnString = Tag.PRODUCT_SECURITY + " " + errorMessage + " " + sqlOrder; return returnString; } }
Example #2
Source File: JSONConverter.java From jcypher with Apache License 2.0 | 6 votes |
/** * Answer a JSON representation of a recorded query * @param query * @return */ public String toJSON(RecordedQuery query) { StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartObject(); writeQuery(query, generator); generator.writeEnd(); generator.flush(); return sw.toString(); }
Example #3
Source File: NovaMinecraftPreloader.java From NOVA-Core with GNU Lesser General Public License v3.0 | 6 votes |
/** * Dynamically generates a sound JSON file based on a resource pack's file structure. * * If it's a folder, then load it as a sound collection. * A sound collection falls under the same resource name. When called to play, it will pick a random sound from the collection to play it. * * If it's just a sound file, then load the sound file * * @param pack The resource pack to generate the sound JSON for. * @return The generated sound JSON. */ public static String generateSoundJSON(AbstractResourcePack pack) { StringWriter sw = new StringWriter(); try (JsonGenerator json = Json.createGenerator(sw);) { json.writeStartObject(); if (pack instanceof FileResourcePack) { //For zip resource packs try { generateSoundJSON((FileResourcePack) pack, json); } catch (Exception e) { Error error = new ExceptionInInitializerError("Error generating fake sound JSON file."); error.addSuppressed(e); throw error; } } else if (pack instanceof FolderResourcePack) { //For folder resource packs generateSoundJSON((FolderResourcePack) pack, json); } json.writeEnd().flush(); return sw.toString(); } }
Example #4
Source File: PersonsIT.java From jaxrs-beanvalidation-javaee7 with Apache License 2.0 | 6 votes |
@Test @RunAsClient @InSequence(10) public void shouldReturnAllPersons(@ArquillianResource URL baseURL) { Client client = ClientBuilder.newBuilder() .register(JsonProcessingFeature.class) .property(JsonGenerator.PRETTY_PRINTING, true) .build(); Response response = client.target(baseURL + "r/persons") .request(MediaType.APPLICATION_JSON) .get(); response.bufferEntity(); logResponse("shouldReturnAllPersons", response, JsonArray.class); Assert.assertEquals(Collections.emptyList(), response.readEntity(new GenericType<Collection<Person>>() {})); }
Example #5
Source File: ConfigData.java From FHIR with Apache License 2.0 | 6 votes |
/** * @param obj * @return * @throws IOException */ public static String generate(ConfigData obj) throws IOException { String o = "{}"; try (StringWriter writer = new StringWriter();) { try (JsonGenerator generator = PRETTY_PRINTING_GENERATOR_FACTORY.createGenerator(writer);) { generator.writeStartObject(); if (obj.getServerStartupParms() != null) { generator.write("server_startup_parameters", obj.getServerStartupParms()); } generator.writeEnd(); } o = writer.toString(); } return o; }
Example #6
Source File: FrontHandler.java From gluon-samples with BSD 3-Clause "New" or "Revised" License | 6 votes |
@RequestMapping(value = "whiteboard", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + "; " + CHARSET) public String whiteboardCreateItem(@RequestParam("title") String title) { Item item = service.createItem(title); cloudLinkService.addItem(item); try (StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = Json.createGenerator(stringWriter)) { jsonGenerator.writeStartObject(); jsonGenerator.write("id", item.getId()); jsonGenerator.write("title", item.getTitle()); jsonGenerator.write("creationDate", item.getCreationDate()); jsonGenerator.writeEnd(); jsonGenerator.close(); return stringWriter.toString(); } catch (IOException e) { e.printStackTrace(); } return "{}"; }
Example #7
Source File: StringBackend.java From jaxrs-analyzer with Apache License 2.0 | 6 votes |
private String format(final String json) { final JsonProvider provider = JsonProvider.provider(); final StringWriter out = new StringWriter(); try (final JsonReader reader = provider.createReader(new StringReader(json)); final JsonWriter jsonWriter = provider.createWriterFactory(singletonMap(JsonGenerator.PRETTY_PRINTING, true)) .createWriter(out)) { // jsonWriter.write(reader.readValue()); // bug in RI, can switch to johnzon final JsonStructure read = reader.read(); if (read.getValueType() == JsonValue.ValueType.OBJECT) { jsonWriter.writeObject(JsonObject.class.cast(read)); } else if (read.getValueType() == JsonValue.ValueType.ARRAY) { jsonWriter.writeArray(JsonArray.class.cast(read)); } else { // no reformatting return json; } return out.toString().trim(); } }
Example #8
Source File: CloudLinkService.java From gluon-samples with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Async public void addItem(Item item) { StringWriter writer = new StringWriter(); try (JsonGenerator generator = Json.createGenerator(writer)) { generator.writeStartObject() .write("title", item.getTitle()) .write("creationDate", item.getCreationDate()) .writeEnd(); } String payload = writer.toString(); System.out.println("Creating Item: " + item.getId() + " with payload " + payload); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity<String> entity = new HttpEntity<>(payload, headers); OAuthRestTemplate restTemplate = new OAuthRestTemplate(resourceDetails); String response = restTemplate.postForObject(CLOUDLINK_ENDPOINT + "/list/items/add/" + item.getId(), entity, String.class); System.out.println("CloudLink Response: " + response); }
Example #9
Source File: SecurityRulesChangeMessage.java From ipst with Mozilla Public License 2.0 | 6 votes |
@Override public void toJson(JsonGenerator generator) { generator.write("workflowId", workflowId); generator.writeStartArray("ruleIds"); for (RuleId ruleId : ruleIds) { generator.writeStartObject(); generator.write("attributeSet", ruleId.getAttributeSet().toString()); generator.writeStartObject("securityIndexId"); generator.write("contingencyId", ruleId.getSecurityIndexId().getContingencyId()); generator.writeStartObject("securityIndexType"); generator.write("name", ruleId.getSecurityIndexId().getSecurityIndexType().name()); generator.write("label", ruleId.getSecurityIndexId().getSecurityIndexType().getLabel()); generator.write("dynamic", ruleId.getSecurityIndexId().getSecurityIndexType().isDynamic()); generator.writeEnd(); generator.writeEnd(); generator.writeEnd(); } generator.writeEnd(); }
Example #10
Source File: NovaMinecraftPreloader.java From NOVA-Core with GNU Lesser General Public License v3.0 | 6 votes |
private static JsonGenerator generateSoundJSON(FolderResourcePack pack, JsonGenerator json) { for (String domain : pack.getResourceDomains()) { //Load all sounds in the assets/domain/sounds/* File folder = getFileForResourcePack(pack, "assets/" + domain + "/sounds/"); if (folder.exists()) { for (File listedFile : folder.listFiles()) { String soundName = listedFile.getName().replaceFirst("\\.[^\\.]+$", ""); json.writeStartObject(soundName); json.write("category", "ambient"); json.writeStartArray("sounds"); if (listedFile.isFile()) { json.write(soundName); } else if (listedFile.isDirectory()) { for (File soundItemFile : listedFile.listFiles()) json.write(soundName + "/" + soundItemFile.getName().replaceFirst("\\.[^\\.]+$", "")); } json.writeEnd().writeEnd(); } } } return json; }
Example #11
Source File: FrontHandler.java From gluon-samples with BSD 3-Clause "New" or "Revised" License | 6 votes |
@RequestMapping(value = "whiteboard", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + "; " + CHARSET) public String whiteboard() { try (StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = Json.createGenerator(stringWriter)) { jsonGenerator.writeStartArray(); service.listItems().stream() .map(item -> Json.createObjectBuilder() .add("id", item.getId()) .add("title", item.getTitle()) .add("creationDate", item.getCreationDate()) .build()) .forEach(jsonGenerator::write); jsonGenerator.writeEnd(); jsonGenerator.close(); return stringWriter.toString(); } catch (IOException e) { e.printStackTrace(); } return "[]"; }
Example #12
Source File: PollingLocationResponse.java From FHIR with Apache License 2.0 | 6 votes |
public static void generate(JsonGenerator generatorOutput, Output output) throws IOException { generatorOutput.writeStartObject(); if (output.getType() != null) { generatorOutput.write("type", output.getType()); } if (output.getUrl() != null) { generatorOutput.write("url", output.getUrl()); } if (output.getCount() != null) { generatorOutput.write("count", Long.parseLong(output.getCount())); } if (output.getInputUrl() != null) { generatorOutput.write("inputUrl", output.getInputUrl()); } generatorOutput.writeEnd(); }
Example #13
Source File: JSONDomainFacade.java From jcypher with Apache License 2.0 | 6 votes |
/** * Answer a JSON representation of the domain model * @return */ public String getDomainModel() { DomainModel model = ((IIntDomainAccess)this.domainAccess).getInternalDomainAccess().getDomainModel(); StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartObject(); generator.write("domainName", model.getDomainName()); writeModel(model, generator); generator.writeEnd(); generator.flush(); return sw.toString(); }
Example #14
Source File: JsonExample.java From aceql-http with GNU Lesser General Public License v2.1 | 6 votes |
/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { StringWriter writer = new StringWriter(); JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(true); JsonGenerator gen = jf.createGenerator(writer); gen.writeStartObject().write("firstName", "Duke") .write("lastName", "Java").write("age", 18) .write("streetAddress", "100 Internet Dr") .write("city", "JavaTown").write("state", "JA") .write("postalCode", "12345") .writeStartArray("phoneNumbers").writeStartObject() .write("type", "mobile").write("number", "111-111-1111") .writeEnd().writeStartObject().write("type", "home") .write("number", "222-222-2222").writeEnd().writeEnd() .writeEnd(); gen.close(); System.out.println(writer.toString()); }
Example #15
Source File: JsonOkReturn.java From aceql-http with GNU Lesser General Public License v2.1 | 6 votes |
/** * Build a Json with name and values from the passed map * * @param namesAndValues * the map of (name, value) to add to the JsonGenerator * @return */ public static String build(Map<String, String> namesAndValues) { if (namesAndValues == null) { throw new NullPointerException("namesAndValues is null"); } JsonGeneratorFactory jf = JsonUtil .getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createGenerator(sw); gen.writeStartObject().write("status", "OK"); for (Map.Entry<String, String> entry : namesAndValues.entrySet()) { //System.out.println(entry.getKey() + "/" + entry.getValue()); gen.write(entry.getKey(), entry.getValue()); } gen.writeEnd(); gen.close(); return sw.toString(); }
Example #16
Source File: CadfEndpoint.java From FHIR with Apache License 2.0 | 6 votes |
public static void generate(CadfEndpoint obj, JsonGenerator generator) throws IOException { generator.writeStartObject(); if (obj.getUrl() != null) { generator.write("url", obj.getUrl()); } if (obj.getName() != null) { generator.write("name", obj.getName()); } if (obj.getPort() != null) { generator.write("port", obj.getPort()); } generator.writeEnd(); }
Example #17
Source File: JSONDBFacade.java From jcypher with Apache License 2.0 | 6 votes |
/** * Answer a JSON representation of the available domains in the database * @return */ public String getDomains() { StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartArray(); List<String> doms = DomainInformation.availableDomains(dbAccess); for (String dom : doms) { generator.write(dom); } generator.writeEnd(); generator.flush(); return sw.toString(); }
Example #18
Source File: JsonUtil.java From geoportal-server-harvester with Apache License 2.0 | 6 votes |
/** * Create a JSON string. * @param structure the structure JsonAoject or JsonArray * @param pretty for pretty print * @return the JSON string */ public static String toJson(JsonStructure structure, boolean pretty) { JsonWriter writer = null; StringWriter result = new StringWriter(); try { Map<String, Object> props = new HashMap<String,Object>(); if (pretty) props.put(JsonGenerator.PRETTY_PRINTING,true); JsonWriterFactory factory = Json.createWriterFactory(props); writer = factory.createWriter(result); writer.write(structure); } finally { try { if (writer != null) writer.close(); } catch (Throwable t) { t.printStackTrace(System.err); } } return result.toString().trim(); }
Example #19
Source File: CadfMapItem.java From FHIR with Apache License 2.0 | 6 votes |
public static void generate(CadfMapItem obj, JsonGenerator generator) throws IOException { generator.writeStartObject(); if (obj.getKey() != null) { generator.write("key", obj.getKey()); } if (obj.getValue() != null) { Object tmpObj = obj.getValue(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream objStream = new ObjectOutputStream(baos);) { objStream.writeObject(tmpObj); generator.write("value", java.util.Base64.getEncoder().encodeToString(baos.toByteArray())); } } generator.writeEnd(); }
Example #20
Source File: JSONWriter.java From jcypher with Apache License 2.0 | 6 votes |
private static void writeLiteral(Object val, JsonGenerator generator) { if (val instanceof String) generator.write(val.toString()); else if (val instanceof Number) { if (val instanceof Long) generator.write((Long)val); else if (val instanceof Integer) generator.write((Integer)val); else if (val instanceof Double) generator.write((Double)val); else if (val instanceof Float) generator.write((Float)val); } else if (val instanceof Boolean) generator.write((Boolean)val); else if (val != null) // handle everything else as a string generator.write(val.toString()); }
Example #21
Source File: PersonsIT.java From jaxrs-beanvalidation-javaee7 with Apache License 2.0 | 6 votes |
@Test @RunAsClient @InSequence(50) public void shouldReturnACreatedPerson(@ArquillianResource URL baseURL) { Person person = new Person(); person.setId(20); person.setName("sam"); Form form = new Form(); form.param("id", String.valueOf(person.getId())); form.param("name", person.getName()); Client client = ClientBuilder.newBuilder() .register(JsonProcessingFeature.class) .property(JsonGenerator.PRETTY_PRINTING, true) .build(); Response response = client.target(baseURL + "r/persons/create") .request(MediaType.APPLICATION_JSON) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED)); response.bufferEntity(); logResponse("shouldReturnACreatedPerson", response, JsonObject.class); Assert.assertEquals(person, response.readEntity(Person.class)); }
Example #22
Source File: RealtimeCargoTrackingService.java From CargoTracker-J12015 with MIT License | 6 votes |
public void onCargoInspected(@Observes @CargoInspected Cargo cargo) { Writer writer = new StringWriter(); try (JsonGenerator generator = Json.createGenerator(writer)) { generator .writeStartObject() .write("trackingId", cargo.getTrackingId().getIdString()) .write("origin", cargo.getOrigin().getName()) .write("destination", cargo.getRouteSpecification().getDestination().getName()) .write("lastKnownLocation", cargo.getDelivery().getLastKnownLocation().getName()) .write("transportStatus", cargo.getDelivery().getTransportStatus().toString()) .writeEnd(); } String jsonValue = writer.toString(); for (Session session : sessions) { try { session.getBasicRemote().sendText(jsonValue); } catch (IOException ex) { logger.log(Level.WARNING, "Unable to publish WebSocket message", ex); } } }
Example #23
Source File: JSONDomainFacade.java From jcypher with Apache License 2.0 | 6 votes |
/** * Answer a JSON object containing the domain name * @return */ public String getDomainName() { DomainModel model = ((IIntDomainAccess)this.domainAccess).getInternalDomainAccess().getDomainModel(); StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartObject(); generator.write("domainName", model.getDomainName()); generator.writeEnd(); generator.flush(); return sw.toString(); }
Example #24
Source File: PersonsIT.java From jaxrs-beanvalidation-javaee7 with Apache License 2.0 | 6 votes |
@Test @RunAsClient @InSequence(20) public void shouldReturnAValidationErrorWhenGettingAPerson(@ArquillianResource URL baseURL) { Client client = ClientBuilder.newBuilder() .register(JsonProcessingFeature.class) .property(JsonGenerator.PRETTY_PRINTING, true) .build(); Response response = client.target(baseURL + "r/persons/{id}") .resolveTemplate("id", "test") .request(MediaType.APPLICATION_JSON) .header("Accept-Language", "en") .get(); response.bufferEntity(); logResponse("shouldReturnAValidationErrorWhenGettingAPerson", response, JsonObject.class); Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); }
Example #25
Source File: FrontHandler.java From gluon-samples with BSD 3-Clause "New" or "Revised" License | 6 votes |
@RequestMapping(value = "whiteboard", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + "; " + CHARSET) public String whiteboard(@RequestParam("title") String title) { Item item = service.createItem(title); try (StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = Json.createGenerator(stringWriter)) { jsonGenerator.writeStartObject(); jsonGenerator.write("id", item.getId()); jsonGenerator.write("title", item.getTitle()); jsonGenerator.write("creationDate", item.getCreationDate()); jsonGenerator.writeEnd(); jsonGenerator.close(); return stringWriter.toString(); } catch (IOException e) { e.printStackTrace(); } return "{}"; }
Example #26
Source File: ProjectLicense.java From sonarqube-licensecheck with Apache License 2.0 | 6 votes |
public static String createString(Collection<ProjectLicense> projectLicenses) { TreeSet<ProjectLicense> projectLicenseSet = new TreeSet<>(); projectLicenseSet.addAll(projectLicenses); StringWriter jsonString = new StringWriter(); JsonGenerator generator = Json.createGenerator(jsonString); generator.writeStartArray(); for (ProjectLicense projectLicense : projectLicenseSet) { generator.writeStartObject(); generator.write("projectKey", projectLicense.getProjectKey()); generator.write("license", projectLicense.getLicense()); generator.write("status", projectLicense.getStatus()); generator.writeEnd(); } generator.writeEnd(); generator.close(); return jsonString.toString(); }
Example #27
Source File: JsonOkReturn.java From aceql-http with GNU Lesser General Public License v2.1 | 6 votes |
/** * Returns a name and a value after the OK * * @return just OK */ public static String build(String name, String value) { if (name == null) { throw new NullPointerException("name is null"); } if (value == null) { throw new NullPointerException("value is null"); } JsonGeneratorFactory jf = JsonUtil .getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createGenerator(sw); gen.writeStartObject().write("status", "OK").write(name, value) .writeEnd(); gen.close(); return sw.toString(); }
Example #28
Source File: JsonUtil.java From aceql-http with GNU Lesser General Public License v2.1 | 5 votes |
/** * JsonGeneratorFactory getter with pretty printing on/off * * @param prettyPrintingif * true, JSON will be pretty printed * @return */ public static JsonGeneratorFactory getJsonGeneratorFactory( boolean prettyPrinting) { Map<String, Object> properties = new HashMap<>(1); if (prettyPrinting) { // Putting any value sets the pretty printing to true... So test // must be done properties.put(JsonGenerator.PRETTY_PRINTING, prettyPrinting); } JsonGeneratorFactory jf = Json.createGeneratorFactory(properties); return jf; }
Example #29
Source File: JSONWriter.java From jcypher with Apache License 2.0 | 5 votes |
private static void writeAsParams(QueryParamSet paramSet, JsonGenerator generator) { for (QueryParam param : paramSet.getQueryParams()) { String key = param.getKey(); Object val = param.getValue(); writeLiteral(key, val, generator); } }
Example #30
Source File: JSONWriter.java From jcypher with Apache License 2.0 | 5 votes |
public static JsonGeneratorFactory getPrettyGeneratorFactory() { if (prettyGeneratorFactory == null) { HashMap<String, Object> prettyConfigMap = new HashMap<String, Object>(); prettyConfigMap.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE); prettyGeneratorFactory = Json.createGeneratorFactory(prettyConfigMap); } return prettyGeneratorFactory; }