Java Code Examples for com.fasterxml.jackson.core.JsonGenerator#copyCurrentEvent()

The following examples show how to use com.fasterxml.jackson.core.JsonGenerator#copyCurrentEvent() . 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: AutodetectPrettyPrintingMarker.java    From logbook with MIT License 6 votes vote down vote up
@Override
protected void writeFieldValue(final JsonGenerator generator) throws IOException {
    final PrettyPrinter prettyPrinter = generator.getPrettyPrinter();

    if (prettyPrinter == null) {
        super.writeFieldValue(generator);
    } else {
        final JsonFactory factory = generator.getCodec().getFactory();

        // append to existing tree event by event
        try (final JsonParser parser = factory.createParser(super.getFieldValue().toString())) {
            while (parser.nextToken() != null) {
                generator.copyCurrentEvent(parser);
            }
        }
    }
}
 
Example 2
Source File: AbstractDDiApiIntegrationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Convert CBOR to JSON equivalent.
 * 
 * @param input
 *            CBOR data to convert
 * @return Equivalent JSON string
 * @throws IOException
 *             Invalid CBOR input
 */
protected static String cborToJson(byte[] input) throws IOException {
    CBORFactory cborFactory = new CBORFactory();
    CBORParser cborParser = cborFactory.createParser(input);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter stringWriter = new StringWriter();
    JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter);
    while (cborParser.nextToken() != null) {
        jsonGenerator.copyCurrentEvent(cborParser);
    }
    jsonGenerator.flush();
    return stringWriter.toString();
}
 
Example 3
Source File: Session.java    From jlibs with Apache License 2.0 6 votes vote down vote up
protected WAMPOutputStream invocationMessage(long requestID, long registrationID, ObjectNode details, JsonParser call) throws Throwable{
    if(ROUTER)
        Debugger.temp("<- InvocationMessage: [%d, %d, %s, ...]", InvocationMessage.ID, requestID, registrationID, details);
    WAMPOutputStream out = router.server.createOutputStream();
    try{
        JsonGenerator json = serialization.mapper().getFactory().createGenerator(out);
        json.writeStartArray();
        json.writeNumber(InvocationMessage.ID);
        json.writeNumber(requestID);
        json.writeNumber(registrationID);
        if(details==null){
            json.writeStartObject();
            json.writeEndObject();
        }else
            json.writeTree(details);
        while(call.nextToken()!=null)
            json.copyCurrentEvent(call);
        json.close();
        return out;
    }catch(Throwable thr){
        out.release();
        throw thr;
    }
}
 
Example 4
Source File: Session.java    From jlibs with Apache License 2.0 6 votes vote down vote up
protected WAMPOutputStream resultMessage(long requestID, JsonParser yield) throws Throwable{
    if(ROUTER)
        Debugger.temp("<- ResultMessage: [%d, %d, ...]", ResultMessage.ID, requestID);
    WAMPOutputStream out = router.server.createOutputStream();
    try{
        JsonGenerator json = serialization.mapper().getFactory().createGenerator(out);
        json.writeStartArray();
        json.writeNumber(ResultMessage.ID);
        json.writeNumber(requestID);
        while(yield.nextToken()!=null)
            json.copyCurrentEvent(yield);
        json.close();
        return out;
    }catch(Throwable thr){
        out.release();
        throw thr;
    }
}
 
Example 5
Source File: Session.java    From jlibs with Apache License 2.0 6 votes vote down vote up
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 6
Source File: JacksonJsonFieldBodyFilter.java    From logbook with MIT License 5 votes vote down vote up
public String filter(final String body) {
    try {
        final JsonParser parser = factory.createParser(body);
        
        final CharArrayWriter writer = new CharArrayWriter(body.length() * 2); // rough estimate of final size
        
        final JsonGenerator generator = factory.createGenerator(writer);
        try {
            while(true) {
                JsonToken nextToken = parser.nextToken();
                if(nextToken == null) {
                    break;
                }

                generator.copyCurrentEvent(parser);
                if(nextToken == JsonToken.FIELD_NAME && fields.contains(parser.getCurrentName())) {
                    nextToken = parser.nextToken();
                    generator.writeString(replacement);
                    if(!nextToken.isScalarValue()) {
                        parser.skipChildren(); // skip children
                    }
                }
            }                    
        } finally {
            parser.close();
            
            generator.close();
        }
        
        return writer.toString();
    } catch(final Exception e) {
        log.trace("Unable to filter body for fields {}, compacting result. `{}`", fields, e.getMessage()); 
        return fallbackCompactor.compact(body);
    }
}
 
Example 7
Source File: JacksonStreamTest.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
/** 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 8
Source File: ProxyResource.java    From presto with Apache License 2.0 4 votes vote down vote up
private static byte[] rewriteResponse(byte[] input, Function<String, String> uriRewriter)
{
    try {
        JsonParser parser = JSON_FACTORY.createParser(input);
        ByteArrayOutputStream out = new ByteArrayOutputStream(input.length * 2);
        JsonGenerator generator = JSON_FACTORY.createGenerator(out);

        JsonToken token = parser.nextToken();
        if (token != START_OBJECT) {
            throw invalidJson("bad start token: " + token);
        }
        generator.copyCurrentEvent(parser);

        while (true) {
            token = parser.nextToken();
            if (token == null) {
                throw invalidJson("unexpected end of stream");
            }

            if (token == END_OBJECT) {
                generator.copyCurrentEvent(parser);
                break;
            }

            if (token == FIELD_NAME) {
                String name = parser.getValueAsString();
                if (!"nextUri".equals(name) && !"partialCancelUri".equals(name)) {
                    generator.copyCurrentStructure(parser);
                    continue;
                }

                token = parser.nextToken();
                if (token != VALUE_STRING) {
                    throw invalidJson(format("bad %s token: %s", name, token));
                }
                String value = parser.getValueAsString();

                value = uriRewriter.apply(value);
                generator.writeStringField(name, value);
                continue;
            }

            throw invalidJson("unexpected token: " + token);
        }

        token = parser.nextToken();
        if (token != null) {
            throw invalidJson("unexpected token after object close: " + token);
        }

        generator.close();
        return out.toByteArray();
    }
    catch (IOException e) {
        throw new ProxyException(e);
    }
}