Java Code Examples for com.fasterxml.jackson.core.JsonGenerator#close()
The following examples show how to use
com.fasterxml.jackson.core.JsonGenerator#close() .
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: DruidQuery.java From calcite with Apache License 2.0 | 6 votes |
/** Generates a JSON string to query metadata about a data source. */ static String metadataQuery(String dataSourceName, List<Interval> intervals) { final StringWriter sw = new StringWriter(); final JsonFactory factory = new JsonFactory(); try { final JsonGenerator generator = factory.createGenerator(sw); generator.writeStartObject(); generator.writeStringField("queryType", "segmentMetadata"); generator.writeStringField("dataSource", dataSourceName); generator.writeBooleanField("merge", true); generator.writeBooleanField("lenientAggregatorMerge", true); generator.writeArrayFieldStart("analysisTypes"); generator.writeString("aggregators"); generator.writeEndArray(); writeFieldIf(generator, "intervals", intervals); generator.writeEndObject(); generator.close(); } catch (IOException e) { throw new RuntimeException(e); } return sw.toString(); }
Example 2
Source File: LandedModal.java From ure with MIT License | 6 votes |
void saveScaper(ULandscaper scaper, String filename) { String path = commander.savePath(); File file = new File(path + filename); try ( FileOutputStream stream = new FileOutputStream(file); ) { JsonFactory jfactory = new JsonFactory(); JsonGenerator jGenerator = jfactory .createGenerator(stream, JsonEncoding.UTF8); jGenerator.setCodec(objectMapper); jGenerator.writeObject(scaper); jGenerator.close(); } catch (IOException e) { e.printStackTrace(); } }
Example 3
Source File: Session.java From jlibs with Apache License 2.0 | 6 votes |
protected WAMPOutputStream errorMessage(int requestType, long requestID, JsonParser error) throws Throwable{ if(ROUTER) Debugger.temp("<- ErrorMessage: [%d, %d, %d, ...]", ErrorMessage.ID, requestType, requestID); WAMPOutputStream out = router.server.createOutputStream(); try{ JsonGenerator json = serialization.mapper().getFactory().createGenerator(out); json.writeStartArray(); json.writeNumber(ErrorMessage.ID); json.writeNumber(requestType); json.writeNumber(requestID); while(error.nextToken()!=null) json.copyCurrentEvent(error); json.close(); return out; }catch(Throwable thr){ out.release(); throw thr; } }
Example 4
Source File: Backup.java From zoocreeper with Apache License 2.0 | 6 votes |
public void backup(OutputStream os) throws InterruptedException, IOException, KeeperException { JsonGenerator jgen = null; ZooKeeper zk = null; try { zk = options.createZooKeeper(LOGGER); jgen = JSON_FACTORY.createGenerator(os); if (options.prettyPrint) { jgen.setPrettyPrinter(new DefaultPrettyPrinter()); } jgen.writeStartObject(); if (zk.exists(options.rootPath, false) == null) { LOGGER.warn("Root path not found: {}", options.rootPath); } else { doBackup(zk, jgen, options.rootPath); } jgen.writeEndObject(); } finally { if (jgen != null) { jgen.close(); } if (zk != null) { zk.close(); } } }
Example 5
Source File: Session.java From jlibs with Apache License 2.0 | 6 votes |
protected WAMPOutputStream errorMessage(int requestType, long requestID, ErrorCode errorCode) throws Throwable{ if(ROUTER) Debugger.temp("<- ErrorMessage: [%d, %d, %d, {}, \"%s\", %s, %s]", ErrorMessage.ID, requestType, requestID, errorCode.uri, errorCode.arguments, errorCode.argumentsKw); WAMPOutputStream out = router.server.createOutputStream(); try{ JsonGenerator json = serialization.mapper().getFactory().createGenerator(out); json.writeStartArray(); json.writeNumber(ErrorMessage.ID); json.writeNumber(requestType); json.writeNumber(requestID); json.writeStartObject(); json.writeEndObject(); json.writeString(errorCode.uri); json.writeTree(errorCode.arguments); json.writeTree(errorCode.argumentsKw); json.writeEndArray(); json.close(); return out; }catch(Throwable thr){ out.release(); throw thr; } }
Example 6
Source File: JsonIOUtil.java From protostuff with Apache License 2.0 | 6 votes |
/** * Serializes the {@code message} into an {@link OutputStream} using the given {@code schema}. * <p> * The {@link LinkedBuffer}'s internal byte array will be used as the primary buffer when writing the message. */ public static <T> void writeTo(OutputStream out, T message, Schema<T> schema, boolean numeric, LinkedBuffer buffer) throws IOException { final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), out, false); final JsonGenerator generator = newJsonGenerator(out, buffer.buffer, 0, false, context); try { writeTo(generator, message, schema, numeric); } finally { generator.close(); } }
Example 7
Source File: SpanServiceElasticsearch.java From hawkular-apm with Apache License 2.0 | 5 votes |
private String serialize(Object object) throws IOException { StringWriter out = new StringWriter(); JsonGenerator gen = mapper.getFactory().createGenerator(out); gen.writeObject(object); gen.close(); out.close(); return out.toString(); }
Example 8
Source File: ElasticsearchFilter.java From Quicksql with MIT License | 5 votes |
String translateMatch(RexNode condition) throws IOException, PredicateAnalyzer.ExpressionNotAnalyzableException { StringWriter writer = new StringWriter(); JsonGenerator generator = mapper.getFactory().createGenerator(writer); QueryBuilders.constantScoreQuery(PredicateAnalyzer.analyze(condition)).writeJson(generator); generator.flush(); generator.close(); return "{\"query\" : " + writer.toString() + "}"; }
Example 9
Source File: Session.java From jlibs with Apache License 2.0 | 5 votes |
protected WAMPOutputStream numbers(int id, long number1) throws Throwable{ WAMPOutputStream out = router.server.createOutputStream(); try{ JsonGenerator json = serialization.mapper().getFactory().createGenerator(out); json.writeStartArray(); json.writeNumber(id); json.writeNumber(number1); json.writeEndArray(); json.close(); return out; }catch(Throwable thr){ out.release(); throw thr; } }
Example 10
Source File: JsonUtil.java From erp-framework with MIT License | 5 votes |
public static String bean2Json(Object obj) { try { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); mapper.writeValue(gen, obj); gen.close(); return sw.toString(); }catch (Exception e){ return null; } }
Example 11
Source File: StringsXML.java From appium_apk_tools with Apache License 2.0 | 5 votes |
public static void toJSON(final ResValuesFile input, final File outputDirectory) throws Exception { String[] paths = input.getPath().split("/"); // always "/" even on Windows final String outName = paths[paths.length - 1].replaceFirst("\\.xml$", ".json"); final File outFile = new File(outputDirectory, outName); p("Saving to: " + outFile); JsonGenerator generator = json.createGenerator( new FileOutputStream(outFile), JsonEncoding.UTF8); // Ensure output stream is auto closed when generator.close() is called. generator.configure(Feature.AUTO_CLOSE_TARGET, true); generator.configure(Feature.AUTO_CLOSE_JSON_CONTENT, true); generator.configure(Feature.FLUSH_PASSED_TO_STREAM, true); generator.configure(Feature.QUOTE_NON_NUMERIC_NUMBERS, true); generator.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true); generator.configure(Feature.QUOTE_FIELD_NAMES, true); // generator.configure(Feature.ESCAPE_NON_ASCII, true); // don't escape non // ascii generator.useDefaultPrettyPrinter(); // ResStringValue extends ResScalarValue which has field mRawValue final Field valueField = ResScalarValue.class.getDeclaredField("mRawValue"); valueField.setAccessible(true); generator.writeStartObject(); for (ResResource resource : input.listResources()) { if (input.isSynthesized(resource)) { continue; } final String name = resource.getResSpec().getName(); // Get the value field from the ResStringValue object. final String value = (String) valueField.get(resource.getValue()); generator.writeStringField(name, value); } generator.writeEndObject(); generator.flush(); generator.close(); }
Example 12
Source File: VespaDocumentOperation.java From vespa with Apache License 2.0 | 5 votes |
/** * Create a JSON Vespa document operation given the supplied fields, * operation and document id template. * * @param op Operation (put, remove, update) * @param docId Document id * @param fields Fields to put in document operation * @return A valid JSON Vespa document operation * @throws IOException ... */ public static String create(Operation op, String docId, Map<String, Object> fields, Properties properties, Schema schema) throws IOException { if (op == null) { return null; } if (docId == null || docId.length() == 0) { return null; } if (fields.isEmpty()) { return null; } // create json format ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator g = new JsonFactory().createGenerator(out, JsonEncoding.UTF8); g.writeStartObject(); g.writeStringField(op.toString(), docId); boolean createIfNonExistent = Boolean.parseBoolean(properties.getProperty(PROPERTY_CREATE_IF_NON_EXISTENT, "false")); if (op == Operation.UPDATE && createIfNonExistent) { writeField("create", true, DataType.BOOLEAN, g, properties, schema, op, 0); } String testSetConditionTemplate = properties.getProperty(TESTSET_CONDITION); if (testSetConditionTemplate != null) { String testSetCondition = TupleTools.toString(fields, testSetConditionTemplate); writeField(TESTSET_CONDITION, testSetCondition, DataType.CHARARRAY, g, properties, schema, op, 0); } if (op != Operation.REMOVE) { writeField("fields", fields, DataType.MAP, g, properties, schema, op, 0); } g.writeEndObject(); g.close(); return out.toString(); }
Example 13
Source File: TransactionJsonService.java From glowroot with Apache License 2.0 | 5 votes |
@GET(path = "/backend/transaction/queries", permission = "agent:transaction:queries") String getQueries(@BindAgentRollupId String agentRollupId, @BindRequest TransactionDataRequest request) throws Exception { AggregateQuery query = toQuery(request, DataKind.QUERY); QueryCollector queryCollector = transactionCommonService.getMergedQueries(agentRollupId, query); List<MutableQuery> queries = queryCollector.getSortedAndTruncatedQueries(); if (queries.isEmpty() && fallBackToLargestAggregates(query)) { // fall back to largest aggregates in case expiration settings have recently changed query = withLargestRollupLevel(query); queryCollector = transactionCommonService.getMergedQueries(agentRollupId, query); queries = queryCollector.getSortedAndTruncatedQueries(); if (ignoreFallBackData(query, queryCollector.getLastCaptureTime())) { // this is probably data from before the requested time period queries = ImmutableList.of(); } } List<Query> queryList = Lists.newArrayList(); for (MutableQuery loopQuery : queries) { queryList.add(ImmutableQuery.builder() .queryType(loopQuery.getType()) .truncatedQueryText(loopQuery.getTruncatedText()) .fullQueryTextSha1(loopQuery.getFullTextSha1()) .totalDurationNanos(loopQuery.getTotalDurationNanos()) .executionCount(loopQuery.getExecutionCount()) .totalRows(loopQuery.hasTotalRows() ? loopQuery.getTotalRows() : null) .build()); } if (queryList.isEmpty() && aggregateRepository.shouldHaveQueries(agentRollupId, query)) { return "{\"overwritten\":true}"; } StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.writeObject(queryList); } finally { jg.close(); } return sb.toString(); }
Example 14
Source File: JsonServiceDocumentWriter.java From odata with Apache License 2.0 | 5 votes |
/** * The main method for Writer. * It builds the service root document according to spec. * * @return output in json * @throws ODataRenderException If unable to render the json service document */ public String buildJson() throws ODataRenderException { LOG.debug("Start building Json service root document"); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField(CONTEXT, getContextURL(uri, entityDataModel)); jsonGenerator.writeArrayFieldStart(VALUE); List<EntitySet> entities = entityDataModel.getEntityContainer().getEntitySets(); for (EntitySet entity : entities) { if (entity.isIncludedInServiceDocument()) { writeObject(jsonGenerator, entity); } } List<Singleton> singletons = entityDataModel.getEntityContainer().getSingletons(); for (Singleton singleton : singletons) { writeObject(jsonGenerator, singleton); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); jsonGenerator.close(); return stream.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new ODataRenderException("It is unable to render service document", e); } }
Example 15
Source File: JacksonStreamTest.java From java-client-api with Apache License 2.0 | 5 votes |
/** Demonstrates how to use a JsonGenerator to stream output that you then persist to the * server using StringHandle (in this case, implicitly via writeAs). */ @Test public void testWriteStream() throws IOException { JacksonParserHandle handle = new JacksonParserHandle(); handle = docMgr.read(ORDER_URI, handle); JsonParser jp = handle.get(); if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } StringWriter jsonWriter = new StringWriter(); JsonGenerator jsonStream = (new ObjectMapper()).getFactory().createGenerator(jsonWriter); // in this sample case we're copying everything up to and excluding the order SerializedString order = new SerializedString("order"); do { jsonStream.copyCurrentEvent(jp); } while ( ! jp.nextFieldName(order) ); jsonStream.flush(); jsonStream.close(); docMgr.writeAs("testWriteStream.json", jsonWriter.toString()); JsonNode originalTree = docMgr.readAs(ORDER_URI, JsonNode.class); JsonNode streamedTree = docMgr.readAs("testWriteStream.json", JsonNode.class); assertEquals("customerName fields don't match", originalTree.get("customerName"), streamedTree.get("customerName")); assertEquals("shipToAddress fields don't match", originalTree.get("shipToAddress"), streamedTree.get("shipToAddress")); assertEquals("billingAddressRequired fields don't match", originalTree.get("billingAddressRequired"), streamedTree.get("billingAddressRequired")); }
Example 16
Source File: ElasticsearchFilter.java From calcite with Apache License 2.0 | 5 votes |
String translateMatch(RexNode condition) throws IOException, PredicateAnalyzer.ExpressionNotAnalyzableException { StringWriter writer = new StringWriter(); JsonGenerator generator = mapper.getFactory().createGenerator(writer); QueryBuilders.constantScoreQuery(PredicateAnalyzer.analyze(condition)).writeJson(generator); generator.flush(); generator.close(); return "{\"query\" : " + writer.toString() + "}"; }
Example 17
Source File: ReadViaCodecTest.java From jackson-jr with Apache License 2.0 | 5 votes |
public void testSimpleList() throws Exception { final String INPUT = "[true,\"abc\"]"; TreeNode node = TREE_CODEC.readTree(_factory.createParser(READ_CONTEXT, INPUT)); assertTrue(node instanceof JrsArray); assertEquals(2, node.size()); // actually, verify with write... final StringWriter writer = new StringWriter(); final JsonGenerator g = _factory.createGenerator(WRITE_CONTEXT, writer); TREE_CODEC.writeTree(g, node); g.close(); assertEquals(INPUT, writer.toString()); }
Example 18
Source File: TransactionJsonService.java From glowroot with Apache License 2.0 | 4 votes |
@GET(path = "/backend/transaction/service-calls", permission = "agent:transaction:serviceCalls") String getServiceCalls(@BindAgentRollupId String agentRollupId, @BindRequest TransactionDataRequest request) throws Exception { AggregateQuery query = toQuery(request, DataKind.SERVICE_CALL); ServiceCallCollector serviceCallCollector = transactionCommonService.getMergedServiceCalls(agentRollupId, query); List<MutableServiceCall> serviceCalls = serviceCallCollector.getSortedAndTruncatedServiceCalls(); if (serviceCalls.isEmpty() && fallBackToLargestAggregates(query)) { // fall back to largest aggregates in case expiration settings have recently changed query = withLargestRollupLevel(query); serviceCallCollector = transactionCommonService.getMergedServiceCalls(agentRollupId, query); serviceCalls = serviceCallCollector.getSortedAndTruncatedServiceCalls(); if (ignoreFallBackData(query, serviceCallCollector.getLastCaptureTime())) { // this is probably data from before the requested time period serviceCalls = ImmutableList.of(); } } List<ServiceCall> serviceCallList = Lists.newArrayList(); for (MutableServiceCall loopServiceCall : serviceCalls) { serviceCallList.add(ImmutableServiceCall.builder() .type(loopServiceCall.getType()) .text(loopServiceCall.getText()) .totalDurationNanos(loopServiceCall.getTotalDurationNanos()) .executionCount(loopServiceCall.getExecutionCount()) .build()); } Collections.sort(serviceCallList, new Comparator<ServiceCall>() { @Override public int compare(ServiceCall left, ServiceCall right) { // sort descending return Doubles.compare(right.totalDurationNanos(), left.totalDurationNanos()); } }); if (serviceCallList.isEmpty() && aggregateRepository.shouldHaveServiceCalls(agentRollupId, query)) { return "{\"overwritten\":true}"; } StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.writeObject(serviceCallList); } finally { jg.close(); } return sb.toString(); }
Example 19
Source File: AlertingService.java From glowroot with Apache License 2.0 | 4 votes |
private void sendPagerDuty(String agentRollupId, String agentRollupDisplay, AlertConfig alertConfig, PagerDutyNotification pagerDutyNotification, long endTime, String subject, String messageText, boolean ok) throws Exception { AlertCondition alertCondition = alertConfig.getCondition(); String dedupKey = getPagerDutyDedupKey(agentRollupId, alertCondition); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator jg = ObjectMappers.create().getFactory().createGenerator(baos); try { jg.writeStartObject(); jg.writeStringField("routing_key", pagerDutyNotification.getPagerDutyIntegrationKey()); jg.writeStringField("dedup_key", dedupKey); if (ok) { jg.writeStringField("event_action", "resolve"); } else { jg.writeStringField("event_action", "trigger"); jg.writeStringField("client", "Glowroot"); jg.writeObjectFieldStart("payload"); jg.writeStringField("summary", subject + "\n\n" + messageText); if (agentRollupId.isEmpty()) { jg.writeStringField("source", InetAddress.getLocalHost().getHostName()); } else { jg.writeStringField("source", agentRollupDisplay); } jg.writeStringField("severity", getPagerDutySeverity(alertConfig.getSeverity())); jg.writeStringField("timestamp", formatAsIso8601(endTime)); switch (alertCondition.getValCase()) { case METRIC_CONDITION: jg.writeStringField("class", "metric: " + alertCondition.getMetricCondition().getMetric()); break; case SYNTHETIC_MONITOR_CONDITION: jg.writeStringField("class", "synthetic monitor"); break; case HEARTBEAT_CONDITION: jg.writeStringField("class", "heartbeat"); break; default: logger.warn("unexpected alert condition: " + alertCondition.getValCase().name()); jg.writeStringField("class", "unknown: " + alertCondition.getValCase().name()); break; } jg.writeEndObject(); } jg.writeEndObject(); } finally { jg.close(); } httpClient.post("https://events.pagerduty.com/v2/enqueue", baos.toByteArray(), "application/json"); }
Example 20
Source File: TableEntitySerializer.java From azure-storage-android with Apache License 2.0 | 3 votes |
/** * Reserved for internal use. Writes an entity to the stream as an JSON resource, leaving the stream open * for additional writing. * * @param outStream * The <code>OutputStream</code> to write the entity to.. * @param entity * The instance implementing {@link TableEntity} to write to the output stream. * @param isTableEntry * A flag indicating the entity is a reference to a table at the top level of the storage service when * <code>true<code> and a reference to an entity within a table when <code>false</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * * @throws StorageException * if a Storage service error occurs. * @throws IOException * if an error occurs while accessing the stream. */ static void writeSingleEntity(final OutputStream outStream, final TableEntity entity, final boolean isTableEntry, final OperationContext opContext) throws StorageException, IOException { JsonGenerator generator = jsonFactory.createGenerator(outStream); try { // write to stream writeJsonEntity(generator, entity, isTableEntry, opContext); } finally { generator.close(); } }