List of usage examples for com.fasterxml.jackson.core JsonGenerator close
@Override public abstract void close() throws IOException;
From source file:com.baidubce.services.bmr.BmrClient.java
/** * Create a cluster with the specified options. * * @param request The request containing all options for creating a BMR cluster. * @return The response containing the ID of the newly created cluster. *//*from ww w. j a v a2 s.c o m*/ public CreateClusterResponse createCluster(CreateClusterRequest request) { checkNotNull(request, "request should not be null."); checkStringNotEmpty(request.getImageType(), "The imageType should not be null or empty string."); checkStringNotEmpty(request.getImageVersion(), "The imageVersion should not be null or empty string."); checkNotNull(request.getInstanceGroups(), "The instanceGroups should not be null."); StringWriter writer = new StringWriter(); try { JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("imageType", request.getImageType()); jsonGenerator.writeStringField("imageVersion", request.getImageVersion()); jsonGenerator.writeArrayFieldStart("instanceGroups"); for (InstanceGroupConfig instanceGroup : request.getInstanceGroups()) { jsonGenerator.writeStartObject(); if (instanceGroup.getName() != null) { jsonGenerator.writeStringField("name", instanceGroup.getName()); } jsonGenerator.writeStringField("type", instanceGroup.getType()); jsonGenerator.writeStringField("instanceType", instanceGroup.getInstanceType()); jsonGenerator.writeNumberField("instanceCount", instanceGroup.getInstanceCount()); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); if (request.getName() != null) { jsonGenerator.writeStringField("name", request.getName()); } if (request.getLogUri() != null) { jsonGenerator.writeStringField("logUri", request.getLogUri()); } jsonGenerator.writeBooleanField("autoTerminate", request.getAutoTerminate()); if (request.getApplications() != null) { jsonGenerator.writeArrayFieldStart("applications"); for (ApplicationConfig application : request.getApplications()) { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("name", application.getName()); jsonGenerator.writeStringField("version", application.getVersion()); if (application.getProperties() != null) { jsonGenerator.writeObjectFieldStart("properties"); for (Map.Entry<String, Object> entry : application.getProperties().entrySet()) { jsonGenerator.writeObjectField(entry.getKey(), entry.getValue()); } jsonGenerator.writeEndObject(); } jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); } if (request.getSteps() != null) { jsonGenerator.writeArrayFieldStart("steps"); for (StepConfig step : request.getSteps()) { jsonGenerator.writeStartObject(); if (step.getName() != null) { jsonGenerator.writeStringField("name", step.getName()); } jsonGenerator.writeStringField("type", step.getType()); jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure()); jsonGenerator.writeObjectFieldStart("properties"); for (Map.Entry<String, String> entry : step.getProperties().entrySet()) { jsonGenerator.writeStringField(entry.getKey(), entry.getValue()); } jsonGenerator.writeEndObject(); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); } jsonGenerator.writeEndObject(); jsonGenerator.close(); } catch (IOException e) { throw new BceClientException("Fail to generate json", e); } byte[] json = null; try { json = writer.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new BceClientException("Fail to get UTF-8 bytes", e); } InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CLUSTER); internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length)); internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json"); internalRequest.setContent(RestartableInputStream.wrap(json)); if (request.getClientToken() != null) { internalRequest.addParameter("clientToken", request.getClientToken()); } return this.invokeHttpClient(internalRequest, CreateClusterResponse.class); }
From source file:api.controller.ApiDocsController.java
@RequestMapping(method = RequestMethod.GET, headers = "Accept=application/json") public @ResponseBody String genDocs() throws IOException { StringWriter sw = new StringWriter(); JsonGenerator g = new JsonFactory().createGenerator(sw); g.useDefaultPrettyPrinter();/*from w w w . ja v a 2 s . co m*/ g.writeStartObject(); g.writeStringField("swagger", "2.0"); g.writeObjectFieldStart("info"); g.writeStringField("title", "Java, SpringMVC, Jetty, Heroku API example"); g.writeStringField("description", "Example of simple microservice for API"); g.writeObjectFieldStart("contact"); g.writeStringField("name", "zedar"); g.writeStringField("url", "https://github.com/zedar"); g.writeEndObject(); g.writeObjectFieldStart("license"); g.writeStringField("name", "Creative Commons 4.0 International"); g.writeStringField("url", "http://creativecommons.org/licenses/by/4.0/"); g.writeEndObject(); g.writeStringField("version", "0.0.1"); g.writeEndObject(); g.writeStringField("host", "api-springmvc-jetty.herokuapp.com"); g.writeStringField("basePath", "/api"); g.writeArrayFieldStart("schemes"); g.writeString("https"); g.writeEndArray(); g.writeObjectFieldStart("paths"); g.writeObjectFieldStart("/actions"); g.writeObjectFieldStart("get"); g.writeArrayFieldStart("tags"); g.writeString("action"); g.writeEndArray(); g.writeStringField("summary", "Find actions with optional query"); g.writeArrayFieldStart("parameters"); g.writeStartObject(); g.writeStringField("name", "query"); g.writeStringField("in", "query"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeEndArray(); g.writeObjectFieldStart("responses"); g.writeObjectFieldStart("200"); g.writeStringField("description", "Response with list of found actions"); g.writeObjectFieldStart("schema"); g.writeStringField("type", "array"); g.writeObjectFieldStart("items"); g.writeStringField("$ref", "#/definitions/Action"); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeObjectFieldStart("default"); g.writeStringField("description", "Unexpected error"); g.writeObjectFieldStart("schema"); g.writeStringField("$ref", "#/definitions/Error"); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeObjectFieldStart("definitions"); g.writeObjectFieldStart("Action"); g.writeArrayFieldStart("required"); g.writeString("id"); g.writeString("name"); g.writeEndArray(); g.writeObjectFieldStart("properties"); g.writeObjectFieldStart("id"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeObjectFieldStart("name"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeObjectFieldStart("description"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeObjectFieldStart("url"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeObjectFieldStart("tags"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeObjectFieldStart("Error"); g.writeArrayFieldStart("required"); g.writeString("code"); g.writeString("message"); g.writeEndArray(); g.writeObjectFieldStart("properties"); g.writeObjectFieldStart("code"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeObjectFieldStart("message"); g.writeStringField("type", "string"); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.writeEndObject(); g.close(); String out = sw.toString(); log.debug("API-DOCS:" + out); return out; }
From source file:com.googlecode.jmxtrans.model.output.StackdriverWriter.java
/** * Take query results, make a JSON String * //from w ww.jav a2s.c o m * @param results List of Result objects * @return a String containing a JSON message, or null if there are no values to report * * @throws IOException if there is some problem generating the JSON, should be uncommon */ private String getGatewayMessage(final List<Result> results) throws IOException { int valueCount = 0; Writer writer = new StringWriter(); JsonGenerator g = jsonFactory.createGenerator(writer); g.writeStartObject(); g.writeNumberField("timestamp", System.currentTimeMillis() / 1000); g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION); g.writeArrayFieldStart("data"); List<String> typeNames = this.getTypeNames(); for (Result metric : results) { Map<String, Object> values = metric.getValues(); if (values != null) { for (Entry<String, Object> entry : values.entrySet()) { if (isNumeric(entry.getValue())) { // we have a numeric value, write a value into the message StringBuilder nameBuilder = new StringBuilder(); // put the prefix if set if (this.prefix != null) { nameBuilder.append(prefix); nameBuilder.append("."); } // put the class name or its alias if available if (!metric.getKeyAlias().isEmpty()) { nameBuilder.append(metric.getKeyAlias()); } else { nameBuilder.append(metric.getClassName()); } // Wildcard "typeNames" substitution String typeName = com.googlecode.jmxtrans.model.naming.StringUtils .cleanupStr(TypeNameValuesStringBuilder.getDefaultBuilder().build(typeNames, metric.getTypeName())); if (typeName != null && typeName.length() > 0) { nameBuilder.append("."); nameBuilder.append(typeName); } // add the attribute name nameBuilder.append("."); nameBuilder.append(metric.getAttributeName()); // put the value name if it differs from the attribute name if (!entry.getKey().equals(metric.getAttributeName())) { nameBuilder.append("."); nameBuilder.append(entry.getKey()); } // check for Float/Double NaN since these will cause the message validation to fail if (entry.getValue() instanceof Float && ((Float) entry.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } if (entry.getValue() instanceof Double && ((Double) entry.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } valueCount++; g.writeStartObject(); g.writeStringField("name", nameBuilder.toString()); g.writeNumberField("value", Double.valueOf(entry.getValue().toString())); // if the metric is attached to an instance, include that in the message if (instanceId != null && !instanceId.isEmpty()) { g.writeStringField("instance", instanceId); } g.writeNumberField("collected_at", metric.getEpoch() / 1000); g.writeEndObject(); } } } } g.writeEndArray(); g.writeEndObject(); g.flush(); g.close(); // return the message if there are any values to report if (valueCount > 0) { return writer.toString(); } else { return null; } }
From source file:org.elasticsearch.client.sniff.ElasticsearchNodesSnifferTests.java
private static SniffResponse buildSniffResponse(ElasticsearchNodesSniffer.Scheme scheme) throws IOException { int numNodes = RandomNumbers.randomIntBetween(getRandom(), 1, 5); List<Node> nodes = new ArrayList<>(numNodes); JsonFactory jsonFactory = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator generator = jsonFactory.createGenerator(writer); generator.writeStartObject();/*from w w w .jav a2 s.c o m*/ if (getRandom().nextBoolean()) { generator.writeStringField("cluster_name", "elasticsearch"); } if (getRandom().nextBoolean()) { generator.writeObjectFieldStart("bogus_object"); generator.writeEndObject(); } generator.writeObjectFieldStart("nodes"); for (int i = 0; i < numNodes; i++) { String nodeId = RandomStrings.randomAsciiOfLengthBetween(getRandom(), 5, 10); String host = "host" + i; int port = RandomNumbers.randomIntBetween(getRandom(), 9200, 9299); HttpHost publishHost = new HttpHost(host, port, scheme.toString()); Set<HttpHost> boundHosts = new HashSet<>(); boundHosts.add(publishHost); if (randomBoolean()) { int bound = between(1, 5); for (int b = 0; b < bound; b++) { boundHosts.add(new HttpHost(host + b, port, scheme.toString())); } } int numAttributes = between(0, 5); Map<String, List<String>> attributes = new HashMap<>(numAttributes); for (int j = 0; j < numAttributes; j++) { int numValues = frequently() ? 1 : between(2, 5); List<String> values = new ArrayList<>(); for (int v = 0; v < numValues; v++) { values.add(j + "value" + v); } attributes.put("attr" + j, values); } Node node = new Node(publishHost, boundHosts, randomAsciiAlphanumOfLength(5), randomAsciiAlphanumOfLength(5), new Node.Roles(randomBoolean(), randomBoolean(), randomBoolean()), attributes); generator.writeObjectFieldStart(nodeId); if (getRandom().nextBoolean()) { generator.writeObjectFieldStart("bogus_object"); generator.writeEndObject(); } if (getRandom().nextBoolean()) { generator.writeArrayFieldStart("bogus_array"); generator.writeStartObject(); generator.writeEndObject(); generator.writeEndArray(); } boolean isHttpEnabled = rarely() == false; if (isHttpEnabled) { nodes.add(node); generator.writeObjectFieldStart("http"); generator.writeArrayFieldStart("bound_address"); for (HttpHost bound : boundHosts) { generator.writeString(bound.toHostString()); } generator.writeEndArray(); if (getRandom().nextBoolean()) { generator.writeObjectFieldStart("bogus_object"); generator.writeEndObject(); } generator.writeStringField("publish_address", publishHost.toHostString()); if (getRandom().nextBoolean()) { generator.writeNumberField("max_content_length_in_bytes", 104857600); } generator.writeEndObject(); } List<String> roles = Arrays.asList(new String[] { "master", "data", "ingest" }); Collections.shuffle(roles, getRandom()); generator.writeArrayFieldStart("roles"); for (String role : roles) { if ("master".equals(role) && node.getRoles().isMasterEligible()) { generator.writeString("master"); } if ("data".equals(role) && node.getRoles().isData()) { generator.writeString("data"); } if ("ingest".equals(role) && node.getRoles().isIngest()) { generator.writeString("ingest"); } } generator.writeEndArray(); generator.writeFieldName("version"); generator.writeString(node.getVersion()); generator.writeFieldName("name"); generator.writeString(node.getName()); if (numAttributes > 0) { generator.writeObjectFieldStart("attributes"); for (Map.Entry<String, List<String>> entry : attributes.entrySet()) { if (entry.getValue().size() == 1) { generator.writeStringField(entry.getKey(), entry.getValue().get(0)); } else { for (int v = 0; v < entry.getValue().size(); v++) { generator.writeStringField(entry.getKey() + "." + v, entry.getValue().get(v)); } } } generator.writeEndObject(); } generator.writeEndObject(); } generator.writeEndObject(); generator.writeEndObject(); generator.close(); return SniffResponse.buildResponse(writer.toString(), nodes); }
From source file:tds.student.web.backing.TestShellScriptsBacking.java
private void addTestSegments() throws IOException, ReturnStatusException { TestSession testSession = StudentContext.getSession(); // _studentSettings = FacesContextHelper.getBean ("studentSettings", // StudentSettings.class); OpportunitySegments oppSegments = null; // load opp segments only if there are any test segments if (_testProps.getSegments().size() > 0) { oppSegments = this._iOpportunityService.getSegments(this._testOpportunity.getOppInstance(), !this._studentSettings.isReadOnly()); }//w w w. j a va 2s.c om StringWriter sw = new StringWriter(); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator writer = jsonFactory.createGenerator(sw); writer.writeStartArray(); // [ for (final TestSegment testSegment : _testProps.getSegments()) { OpportunitySegment oppSegment = null; // find opportunity segment if (oppSegments != null) { oppSegment = (OpportunitySegment) CollectionUtils.find(oppSegments, new Predicate() { @Override public boolean evaluate(Object arg0) { if (StringUtils.equals(((OpportunitySegment) arg0).getId(), testSegment.getId())) return true; return false; } }); } // figure out segment permeability int isPermeable = testSegment.getIsPermeable(); int updatePermeable = isPermeable; // these are local override rules (reviewed with Larry) if (oppSegment != null) { /* * if -1, use the defined value for the segment as returned by * IB_GetSegments if not -1, then the local value defines the temporary * segment permeability */ if (oppSegment.getIsPermeable() != -1) { isPermeable = oppSegment.getIsPermeable(); /* * The default permeability is restored when the student leaves the * segment while testing. Assuming the segment is impermeable, this * allows the student one entry into the segment during the sitting. * When the student leaves the segment, is membrane is enforced by the * student app. The database will restore the default value of the * segment membrane when the test is paused. */ if (oppSegment.getRestorePermOn() != "segment") { updatePermeable = oppSegment.getIsPermeable(); } } // NOTE: When student enters segment, set isPermeable = updatePermeable } // if read only mode is enabled then we should let user have access if (_studentSettings.isReadOnly()) { isPermeable = 1; updatePermeable = 1; } // figure out segment approval int entryApproval = testSegment.getEntryApproval(); int exitApproval = testSegment.getExitApproval(); // NOTE: If proctorless test then don't require entry/exit approval // (nobody to approve it) if (testSession.isProctorless() || _studentSettings.isReadOnly()) { entryApproval = 0; exitApproval = 0; } // BUG #22642: Entry and Exit approvals are not needed from Test level // review screen when approval = 2 else if (getViewPageNumber() > 0) { if (testSegment.getEntryApproval() == 2) entryApproval = 0; if (testSegment.getExitApproval() == 2) exitApproval = 0; } // write segment json writer.writeStartObject(); writer.writeStringField("type", "object"); // { writer.writeStringField("id", testSegment.getId()); writer.writeNumberField("position", testSegment.getPosition()); writer.writeStringField("label", testSegment.getLabel()); writer.writeBooleanField("itemReview", testSegment.isItemReview()); writer.writeNumberField("isPermeable", isPermeable); writer.writeNumberField("updatePermeable", updatePermeable); writer.writeNumberField("entryApproval", entryApproval); writer.writeNumberField("exitApproval", exitApproval); // Looks like we don't use this variable in javascript (removed for 2012) // Test adaptiveSegment = // TestOpportunity.AdaptiveTest.GetSegmentTest(testSegment.ID); // writer.WriteObject("length", (adaptiveSegment != null) ? // adaptiveSegment.TotalMinLength : 0); writer.writeEndObject(); // } } writer.writeEndArray(); // ] writer.close(); // write out javascript StringBuilder javascript = new StringBuilder(); javascript.append("var tdsSegments = "); javascript.append(sw.toString()); javascript.append("; "); this.getClientScript().addToJsCode(javascript.toString()); }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
public String marshall(Definitions def, String preProcessingData) throws IOException { DroolsPackageImpl.init();// w w w. ja v a 2s . co m BpsimPackageImpl.init(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonFactory f = new JsonFactory(); JsonGenerator generator = f.createJsonGenerator(baos, JsonEncoding.UTF8); if (def.getRelationships() != null && def.getRelationships().size() > 0) { // current support for single relationship Relationship relationship = def.getRelationships().get(0); for (ExtensionAttributeValue extattrval : relationship.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<BPSimDataType> bpsimExtensions = (List<BPSimDataType>) extensionElements .get(BpsimPackage.Literals.DOCUMENT_ROOT__BP_SIM_DATA, true); if (bpsimExtensions != null && bpsimExtensions.size() > 0) { BPSimDataType processAnalysis = bpsimExtensions.get(0); if (processAnalysis.getScenario() != null && processAnalysis.getScenario().size() > 0) { _simulationScenario = processAnalysis.getScenario().get(0); } } } } if (preProcessingData == null || preProcessingData.length() < 1) { preProcessingData = "ReadOnlyService"; } // this is a temp way to determine if // coordinate system changes are necessary String bpmn2Exporter = def.getExporter(); String bpmn2ExporterVersion = def.getExporterVersion(); boolean haveExporter = bpmn2Exporter != null && bpmn2ExporterVersion != null; if (_simulationScenario != null && !haveExporter) { coordianteManipulation = false; } marshallDefinitions(def, generator, preProcessingData); generator.close(); return baos.toString("UTF-8"); }
From source file:net.opentsdb.tsd.HttpSampleSerializer.java
/** * Format the results from a timeseries data query * @param data_query The TSQuery object used to fetch the results * @param results The data fetched from storage * @param globals An optional list of global annotation objects * @return A ChannelBuffer object to pass on to the caller *///from w ww. j a va 2 s .c o m public ChannelBuffer formatQueryV1(final TSQuery data_query, final List<DataPoints[]> results, final List<Annotation> globals) { final boolean as_arrays = this.query.hasQueryStringParam("arrays"); final String jsonp = this.query.getQueryStringParam("jsonp"); // todo - this should be streamed at some point since it could be HUGE final ChannelBuffer response = ChannelBuffers.dynamicBuffer(); final OutputStream output = new ChannelBufferOutputStream(response); try { // don't forget jsonp if (jsonp != null && !jsonp.isEmpty()) { output.write((jsonp + "(").getBytes(query.getCharset())); } JsonGenerator json = JSON.getFactory().createGenerator(output); json.writeStartArray(); for (DataPoints[] separate_dps : results) { for (DataPoints dps : separate_dps) { json.writeStartObject(); json.writeStringField("metric", dps.metricName()); json.writeFieldName("tags"); json.writeStartObject(); if (dps.getTags() != null) { for (Map.Entry<String, String> tag : dps.getTags().entrySet()) { json.writeStringField(tag.getKey(), tag.getValue()); } } json.writeEndObject(); json.writeFieldName("aggregateTags"); json.writeStartArray(); if (dps.getAggregatedTags() != null) { for (String atag : dps.getAggregatedTags()) { json.writeString(atag); } } json.writeEndArray(); if (data_query.getShowTSUIDs()) { json.writeFieldName("tsuids"); json.writeStartArray(); final List<String> tsuids = dps.getTSUIDs(); Collections.sort(tsuids); for (String tsuid : tsuids) { json.writeString(tsuid); } json.writeEndArray(); } if (!data_query.getNoAnnotations()) { final List<Annotation> annotations = dps.getAnnotations(); if (annotations != null) { Collections.sort(annotations); json.writeArrayFieldStart("annotations"); for (Annotation note : annotations) { json.writeObject(note); } json.writeEndArray(); } if (globals != null && !globals.isEmpty()) { Collections.sort(globals); json.writeArrayFieldStart("globalAnnotations"); for (Annotation note : globals) { json.writeObject(note); } json.writeEndArray(); } } // now the fun stuff, dump the data json.writeFieldName("dps"); // default is to write a map, otherwise write arrays if (as_arrays) { json.writeStartArray(); for (final DataPoint dp : dps) { if (dp.timestamp() < data_query.startTime() || dp.timestamp() > data_query.endTime()) { continue; } final long timestamp = data_query.getMsResolution() ? dp.timestamp() : dp.timestamp() / 1000; json.writeStartArray(); json.writeNumber(timestamp); json.writeNumber(dp.isInteger() ? dp.longValue() : dp.doubleValue()); json.writeEndArray(); } json.writeEndArray(); } else { json.writeStartObject(); for (final DataPoint dp : dps) { if (dp.timestamp() < (data_query.startTime()) || dp.timestamp() > (data_query.endTime())) { continue; } final long timestamp = data_query.getMsResolution() ? dp.timestamp() : dp.timestamp() / 1000; json.writeNumberField(Long.toString(timestamp), dp.isInteger() ? dp.longValue() : dp.doubleValue()); } json.writeEndObject(); } // close the results for this particular query json.writeEndObject(); } } // close json.writeEndArray(); json.close(); if (jsonp != null && !jsonp.isEmpty()) { output.write(")".getBytes()); } return response; } catch (IOException e) { LOG.error("Unexpected exception", e); throw new RuntimeException(e); } }
From source file:eionet.meta.exports.json.VocabularyJSONOutputHelper.java
/** * Writes JSON to output stream./*from w w w .ja v a 2 s .c o m*/ * <p> * NOTE: For readability purposes, nested blocks are used in this method while generating json contents. * </p> * * @param out * output stream * @param vocabulary * vocabulary base uri * @param concepts * list of vocabulary concepts * @param language * language for the preferred label * @throws java.io.IOException * if error in I/O */ public static void writeJSON(OutputStream out, VocabularyFolder vocabulary, List<VocabularyConcept> concepts, String language) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8"); JsonFactory f = new JsonFactory(); JsonGenerator generator = f.createGenerator(out); generator.useDefaultPrettyPrinter(); language = StringUtils.trimToNull(language); boolean checkLanguage = StringUtils.isNotBlank(language); List<String> relationalDataElemIdentifiers = new ArrayList<String>(); relationalDataElemIdentifiers.add(BROADER); relationalDataElemIdentifiers.add(NARROWER); // start json object generator.writeStartObject(); // add context generator.writeObjectFieldStart(JSON_LD_CONTEXT); { generator.writeStringField(JSON_LD_BASE, VocabularyFolder.getBaseUri(vocabulary)); generator.writeStringField(VocabularyOutputHelper.LinkedDataNamespaces.SKOS, VocabularyOutputHelper.LinkedDataNamespaces.SKOS_NS); generator.writeStringField(JSON_LD_CONCEPTS, SKOS_CONCEPT); generator.writeStringField(PREF_LABEL, SKOS_PREF_LABEL); for (String dataElemShortIdentifier : relationalDataElemIdentifiers) { generator.writeStringField(dataElemShortIdentifier, DATA_ELEM_MAP.get(dataElemShortIdentifier)); } generator.writeStringField(JSON_LD_LANGUAGE, StringUtils.isNotBlank(language) ? language : DEFAULT_LANGUAGE); } generator.writeEndObject(); // start writing concepts... generator.writeArrayFieldStart(JSON_LD_CONCEPTS); // iterate on concepts for (VocabularyConcept concept : concepts) { generator.writeStartObject(); { generator.writeStringField(JSON_LD_ID, concept.getIdentifier()); generator.writeStringField(JSON_LD_TYPE, SKOS_CONCEPT); // start writing prefLabels generator.writeArrayFieldStart(PREF_LABEL); { String label; String labelLang; if (checkLanguage) { List<DataElement> dataElementValuesByNameAndLang = VocabularyOutputHelper .getDataElementValuesByNameAndLang(SKOS_PREF_LABEL, language, concept.getElementAttributes()); if (dataElementValuesByNameAndLang != null && dataElementValuesByNameAndLang.size() > 0) { label = dataElementValuesByNameAndLang.get(0).getAttributeValue(); labelLang = language; } else { dataElementValuesByNameAndLang = VocabularyOutputHelper .getDataElementValuesByNameAndLang(SKOS_PREF_LABEL, DEFAULT_LANGUAGE, concept.getElementAttributes()); if (dataElementValuesByNameAndLang != null && dataElementValuesByNameAndLang.size() > 0) { label = dataElementValuesByNameAndLang.get(0).getAttributeValue(); } else { label = concept.getLabel(); } labelLang = DEFAULT_LANGUAGE; } generator.writeStartObject(); { generator.writeStringField(JSON_LD_VALUE, label); generator.writeStringField(JSON_LD_LANGUAGE, labelLang); } generator.writeEndObject(); } else { generator.writeStartObject(); { generator.writeStringField(JSON_LD_VALUE, concept.getLabel()); generator.writeStringField(JSON_LD_LANGUAGE, DEFAULT_LANGUAGE); } generator.writeEndObject(); List<DataElement> dataElementValuesByName = VocabularyOutputHelper .getDataElementValuesByName(SKOS_PREF_LABEL, concept.getElementAttributes()); if (dataElementValuesByName != null && dataElementValuesByName.size() > 0) { for (DataElement elem : dataElementValuesByName) { generator.writeStartObject(); { generator.writeStringField(JSON_LD_VALUE, elem.getAttributeValue()); generator.writeStringField(JSON_LD_LANGUAGE, elem.getAttributeLanguage()); } generator.writeEndObject(); } } } } // end writing prefLabels generator.writeEndArray(); // write data elements for (String shortDataElemIdentifier : relationalDataElemIdentifiers) { // check if it has this element List<DataElement> dataElementValuesByName = VocabularyOutputHelper.getDataElementValuesByName( DATA_ELEM_MAP.get(shortDataElemIdentifier), concept.getElementAttributes()); if (dataElementValuesByName != null && dataElementValuesByName.size() > 0) { // start writing element values generator.writeArrayFieldStart(shortDataElemIdentifier); for (DataElement elem : dataElementValuesByName) { generator.writeStartObject(); { generator.writeStringField(JSON_LD_ID, elem.getRelatedConceptIdentifier()); } generator.writeEndObject(); } // end writing element values generator.writeEndArray(); } } } // end writing concept generator.writeEndObject(); } // end of iteration on concepts generator.writeEndArray(); // end of vocabulary name generator.writeEndObject(); // close writer and stream generator.close(); osw.close(); }