com.fasterxml.jackson.core.JsonGenerator#close ( )源码实例Demo

下面列出了com.fasterxml.jackson.core.JsonGenerator#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jlibs   文件: Session.java
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;
    }
}
 
源代码2 项目: protostuff   文件: JsonIOUtil.java
/**
 * 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();
    }
}
 
源代码3 项目: calcite   文件: DruidQuery.java
/** 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();
}
 
源代码4 项目: zoocreeper   文件: Backup.java
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();
        }
    }
}
 
源代码5 项目: jlibs   文件: Session.java
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;
    }
}
 
源代码6 项目: ure   文件: LandedModal.java
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();
    }
}
 
源代码7 项目: jackson-jr   文件: ReadViaCodecTest.java
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());
}
 
源代码8 项目: glowroot   文件: TransactionJsonService.java
@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();
}
 
源代码9 项目: erp-framework   文件: JsonUtil.java
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;
    }

}
 
源代码10 项目: jlibs   文件: Session.java
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;
    }
}
 
源代码11 项目: hawkular-apm   文件: SpanServiceElasticsearch.java
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();
}
 
源代码12 项目: Quicksql   文件: ElasticsearchFilter.java
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() + "}";
}
 
源代码13 项目: appium_apk_tools   文件: StringsXML.java
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();
}
 
源代码14 项目: vespa   文件: VespaDocumentOperation.java
/**
 * 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();
}
 
源代码15 项目: odata   文件: JsonServiceDocumentWriter.java
/**
 * 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);
    }
}
 
源代码16 项目: java-client-api   文件: JacksonStreamTest.java
/** 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"));
}
 
源代码17 项目: calcite   文件: ElasticsearchFilter.java
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() + "}";
}
 
源代码18 项目: glowroot   文件: AlertingService.java
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");
}
 
源代码19 项目: glowroot   文件: TransactionJsonService.java
@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();
}
 
/**
 * 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();
    }
}