List of usage examples for com.fasterxml.jackson.core JsonGenerator flush
@Override public abstract void flush() throws IOException;
From source file:com.predic8.membrane.core.interceptor.statistics.StatisticsProvider.java
private void createJson(Exchange exc, ResultSet r, int offset, int max, int total) throws IOException, JsonGenerationException, SQLException { StringWriter jsonTxt = new StringWriter(); JsonGenerator jsonGen = jsonFactory.createGenerator(jsonTxt); jsonGen.writeStartObject();//w ww. j av a2 s .c o m jsonGen.writeArrayFieldStart("statistics"); int size = 0; r.absolute(offset + 1); //jdbc doesn't support paginating. This can be inefficient. while (size < max && !r.isAfterLast()) { size++; writeRecord(r, jsonGen); r.next(); } jsonGen.writeEndArray(); jsonGen.writeNumberField("total", total); jsonGen.writeEndObject(); jsonGen.flush(); createResponse(exc, jsonTxt); }
From source file:org.killbill.billing.plugin.meter.api.user.JsonSamplesOutputer.java
protected void output(final OutputStream output, final List<Integer> sourceIds, final List<Integer> metricIds, final DateTime startTime, final DateTime endTime) throws IOException { // Setup Jackson final JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(output); generator.writeStartArray();//from ww w . ja v a 2s .com // First, return all data stored in the database writeJsonForStoredChunks(generator, sourceIds, metricIds, startTime, endTime); // Now return all data in memory writeJsonForInMemoryChunks(generator, sourceIds, metricIds, startTime, endTime); // Allow implementers to flush their buffers writeRemainingData(generator); generator.writeEndArray(); generator.flush(); generator.close(); }
From source file:com.ning.metrics.action.hdfs.reader.HdfsListing.java
@SuppressWarnings({ "unchecked", "unused" }) public void toJson(final OutputStream out, final boolean pretty) throws IOException { final String parentPath = getParentPath() == null ? "" : getParentPath(); final JsonGenerator generator = new JsonFactory().createJsonGenerator(out); generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); if (pretty) { generator.setPrettyPrinter(new DefaultPrettyPrinter()); }/*from w w w. j a v a 2 s. c o m*/ generator.writeStartObject(); generator.writeObjectField(JSON_LISTING_PATH, getPath()); generator.writeObjectField(JSON_LISTING_PARENT_PATH, parentPath); generator.writeArrayFieldStart(JSON_LISTING_ENTRIES); // Important: need to flush before appending pre-serialized events generator.flush(); for (HdfsEntry entry : getEntries()) { entry.toJson(generator); } generator.writeEndArray(); generator.writeEndObject(); generator.close(); }
From source file:com.cinnober.msgcodec.json.JsonCodec.java
/** * Write the group to the byte sink, but without adding the '$type' field. * To decode the JSON the receiver must know what group type to expect. * * @param group the group to encode.//www .ja va2s . c o m * @param out the byte sink to write to, not null. * @throws IOException if the underlying byte sink throws an exception. * @throws IllegalArgumentException if the group is not correct or complete, e.g. a required field is missing. * Partial data may have been written to the byte sink. */ public void encodeStatic(Object group, ByteSink out) throws IOException { if (group == null) { out.write(NULL_BYTES); } else { JsonFactory f = new JsonFactory(); JsonGenerator g = f.createGenerator(new ByteSinkOutputStream(out)); StaticGroupHandler groupHandler = lookupGroupByValue(group); if (groupHandler == null) { throw new IllegalArgumentException("Cannot encode group (unknown type)"); } groupHandler.writeValue(group, g, false); g.flush(); } }
From source file:com.google.openrtb.json.OpenRtbNativeJsonWriter.java
/** * Serializes a {@link NativeRequest} to JSON, with a provided {@link JsonGenerator} * which allows several choices of output and encoding. *//*from w w w . j a v a 2 s . c o m*/ public final void writeNativeRequest(NativeRequest req, JsonGenerator gen) throws IOException { gen.writeStartObject(); if (factory().isRootNativeField()) { gen.writeObjectFieldStart("native"); } writeNativeRequestFields(req, gen); writeExtensions(req, gen); if (factory().isRootNativeField()) { gen.writeEndObject(); } gen.writeEndObject(); gen.flush(); }
From source file:org.mashti.jetson.json.JsonResponseEncoder.java
void encodeResultOrException(final Integer id, final Object result, final Throwable exception, final ByteBuf out, final boolean error) throws RPCException { JsonGenerator generator = null; try {//from w w w. j av a 2s . co m generator = createJsonGenerator(out); generator.writeStartObject(); generator.writeObjectField(JsonRequestEncoder.ID_KEY, id); generator.writeObjectField(JsonRequestEncoder.VERSION_KEY, JsonRequestEncoder.DEFAULT_VERSION); if (error) { final JsonRpcError json_rpc_error = JsonRpcExceptions.toJsonRpcError(exception); generator.writeObjectField(ERROR_KEY, json_rpc_error); } else { generator.writeObjectField(RESULT_KEY, result); } generator.writeEndObject(); generator.flush(); generator.close(); } catch (final JsonProcessingException e) { LOGGER.debug("failed to encode response", e); throw new InternalServerException(e); } catch (final IOException e) { LOGGER.debug("IO error occurred while encoding response", e); throw new TransportException(e); } finally { CloseableUtil.closeQuietly(generator); } }
From source file:com.jxt.web.util.MappingJackson2JsonpView.java
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Object value = filterModel(model); JsonGenerator generator = this.objectMapper.getFactory().createGenerator(response.getOutputStream(), this.encoding); if (this.prefixJson) { generator.writeRaw("{} && "); }//ww w .ja va2 s .com final String callBackParameter = getCallBackParameter(request); if (StringUtils.isEmpty(callBackParameter)) { this.objectMapper.writeValue(generator, value); } else { generator.writeRaw(callBackParameter); generator.writeRaw(cbPrefix); this.objectMapper.writeValue(generator, value); generator.writeRaw(cbSuffix); generator.writeRaw(cbEnd); } generator.flush(); }
From source file:com.google.openrtb.json.OpenRtbNativeJsonWriter.java
/** * Serializes a {@link NativeResponse} to JSON, with a provided {@link JsonGenerator} * which allows several choices of output and encoding. *//*from ww w . ja v a 2s .c o m*/ public final void writeNativeResponse(NativeResponse resp, JsonGenerator gen) throws IOException { gen.writeStartObject(); if (factory().isRootNativeField()) { gen.writeObjectFieldStart("native"); } writeNativeResponseFields(resp, gen); writeExtensions(resp, gen); if (factory().isRootNativeField()) { gen.writeEndObject(); } gen.writeEndObject(); gen.flush(); }
From source file:org.usrz.libs.webtools.resources.ServeResource.java
private Response produce(String path) throws Exception { /* Basic check for null/empty path */ if ((path == null) || (path.length() == 0)) return NOT_FOUND; /* Get our resource file, potentially a ".less" file for CSS */ Resource resource = manager.getResource(path); if ((resource == null) && path.endsWith(".css")) { path = path.substring(0, path.length() - 4) + ".less"; resource = manager.getResource(path); }//from w ww . j a v a 2 s.co m /* If the root is incorrect, log this, if not found, 404 it! */ if (resource == null) return NOT_FOUND; /* Ok, we have a resource on disk, this can be potentially long ... */ final String fileName = resource.getFile().getName(); /* Check and validated our cache */ Entry cached = cache.computeIfPresent(resource, (r, entry) -> entry.resource.hasChanged() ? null : entry); /* If we have no cache, we *might* want to cache something */ if (cached == null) { /* What to do, what to do? */ if ((fileName.endsWith(".css") && minify) || fileName.endsWith(".less")) { /* Lessify CSS and cache */ xlog.debug("Lessifying resource \"%s\"", fileName); cached = new Entry(resource, lxess.convert(resource, minify), styleMediaType); } else if (fileName.endsWith(".js") && minify) { /* Uglify JavaScript and cache */ xlog.debug("Uglifying resource \"%s\"", fileName); cached = new Entry(resource, uglify.convert(resource.readString(), minify, minify), scriptMediaType); } else if (fileName.endsWith(".json")) { /* Strip comments and normalize JSON */ xlog.debug("Normalizing JSON resource \"%s\"", fileName); /* All to do with Jackson */ final Reader reader = resource.read(); final StringWriter writer = new StringWriter(); final JsonParser parser = json.createParser(reader); final JsonGenerator generator = json.createGenerator(writer); /* Not minifying? Means pretty printing! */ if (!minify) generator.useDefaultPrettyPrinter(); /* Get our schtuff through the pipeline */ parser.nextToken(); generator.copyCurrentStructure(parser); generator.flush(); generator.close(); reader.close(); parser.close(); /* Cached results... */ cached = new Entry(resource, writer.toString(), jsonMediaType); } /* Do we have anything to cache? */ if (cached != null) { xlog.debug("Caching resource \"%s\"", fileName); cache.put(resource, cached); } } /* Prepare our basic response from either cache or file */ final ResponseBuilder response = Response.ok(); if (cached != null) { /* Response from cache */ xlog.trace("Serving cached resource \"%s\"", fileName); response.entity(cached.contents).lastModified(new Date(resource.lastModifiedAt())).type(cached.type); } else { /* Response from a file */ xlog.trace("Serving file-based resource \"%s\"", fileName); /* If text/* or application/javascript, append encoding */ MediaType type = MediaTypes.get(fileName); if (type.getType().equals("text") || scriptMediaType.isCompatible(type)) { type = type.withCharset(charsetName); } /* Our file is served! */ response.entity(resource.getFile()).lastModified(new Date(resource.lastModifiedAt())).type(type); } /* Caching headers and build response */ final Date expires = Date.from(Instant.now().plus(cacheDuration)); return response.cacheControl(cacheControl).expires(expires).build(); }
From source file:io.airlift.event.client.JsonEventWriter.java
public <T> void writeEvents(EventClient.EventGenerator<T> events, OutputStream out) throws IOException { Preconditions.checkNotNull(events, "events is null"); Preconditions.checkNotNull(out, "out is null"); final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8); jsonGenerator.writeStartArray();/* www . ja v a 2 s . c om*/ events.generate(new EventClient.EventPoster<T>() { @Override public void post(T event) throws IOException { JsonSerializer<T> serializer = getSerializer(event); if (serializer == null) { throw new InvalidEventException("Event class [%s] has not been registered as an event", event.getClass().getName()); } serializer.serialize(event, jsonGenerator, null); } }); jsonGenerator.writeEndArray(); jsonGenerator.flush(); }