Example usage for com.fasterxml.jackson.dataformat.smile SmileFactory SmileFactory

List of usage examples for com.fasterxml.jackson.dataformat.smile SmileFactory SmileFactory

Introduction

In this page you can find the example usage for com.fasterxml.jackson.dataformat.smile SmileFactory SmileFactory.

Prototype

public SmileFactory() 

Source Link

Document

Default constructor used to create factory instances.

Usage

From source file:com.proofpoint.jaxrs.TestSmileMapper.java

@Override
protected void assertEncodedProperly(byte[] encoded, MultivaluedMap<String, Object> headers, String expected)
        throws IOException {
    ObjectMapper smileMapper = new ObjectMapper(new SmileFactory());
    assertEquals(smileMapper.readValue(encoded, String.class), expected);
}

From source file:com.basistech.AfterburnerOopsTest.java

@Test
public void oops() throws Exception {
    SmileFactory smileFactory = new SmileFactory();
    ObjectMapper mapper = new ObjectMapper(smileFactory);
    mapper = AnnotatedDataModelModule.setupObjectMapper(mapper);

    EntityMention em = new EntityMention();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    List<EntityMention> mentions = Lists.newArrayList();
    mentions.add(em);//from  ww  w  .j a v  a2 s  .  c o  m
    mapper.writeValue(byteArrayOutputStream, mentions);

    mapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper(smileFactory));
    mapper.registerModule(new AfterburnerModule());
    JsonParser jp = smileFactory.createParser(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
    jp.setCodec(mapper);

    JsonToken current;
    current = jp.nextToken();
    if (current != JsonToken.START_ARRAY) {
        System.err.println("Error: root should be array: quiting.");
        return;
    }

    while (jp.nextToken() != JsonToken.END_ARRAY) {
        jp.readValueAs(EntityMention.class);
    }

}

From source file:com.ning.metrics.serialization.smile.TestSmileOutputStream.java

@BeforeTest
public void setUp() throws IOException {
    // Use same configuration as SmileEnvelopeEvent
    f = new SmileFactory();
    f.configure(SmileGenerator.Feature.CHECK_SHARED_NAMES, true);
    f.configure(SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES, true);
    f.configure(SmileParser.Feature.REQUIRE_HEADER, false);
}

From source file:com.raythos.sentilexo.persistence.cql.PersistedEntity.java

public static PersistedEntity fromBinaryJSon(byte[] data, Class classType) {
    try {//from  w w  w  .  ja  v  a 2 s. c om
        SmileFactory f = new SmileFactory();
        f.configure(SmileParser.Feature.REQUIRE_HEADER, true);

        ObjectMapper mapper = new ObjectMapper(f);

        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        Object result = mapper.readValue(data, classType);
        return (PersistedEntity) result;
    } catch (IOException ex) {
        Logger.getLogger(PersistedEntity.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.nesscomputing.jackson.NessJacksonModule.java

@Override
public void configure() {
    // Annotated version (@Json) is also bound to json.
    bind(ObjectMapper.class).annotatedWith(JsonMapper.class).toProvider(NessObjectMapperProvider.class)
            .in(Scopes.SINGLETON);/*from w  ww .ja v a  2 s.com*/

    // Annotated version (@Smile) is bound to the smile factory.
    bind(ObjectMapper.class).annotatedWith(SmileMapper.class)
            .toProvider(new NessObjectMapperProvider(new SmileFactory())).in(Scopes.SINGLETON);

    // Default (not annotated) instance is bound to json.
    bind(ObjectMapper.class).toProvider(NessObjectMapperProvider.class).in(Scopes.SINGLETON);

    bind(NessJacksonConfig.class).toProvider(ConfigProvider.of(NessJacksonConfig.class)).in(Scopes.SINGLETON);

    NessObjectMapperBinder.bindJacksonModule(binder()).toInstance(new GuavaModule());
    NessObjectMapperBinder.bindJacksonModule(binder()).toInstance(new JodaModule());

    install(new NessCustomSerializerModule());

    // MrBean is pretty safe to globally install, since it only deserializes types that would otherwise fail.
    NessObjectMapperBinder.bindJacksonModule(binder()).to(MrBeanModule.class);

    NessObjectMapperBinder.bindJacksonModule(binder()).to(AfterburnerModule.class);
}

From source file:com.opentable.jackson.OpenTableJacksonModule.java

@Override
public void configure() {
    // Annotated version (@Json) is also bound to json.
    bind(ObjectMapper.class).annotatedWith(JsonMapper.class).toProvider(OpenTableObjectMapperProvider.class)
            .in(Scopes.SINGLETON);/*from   w  ww.ja va 2 s  .  c om*/

    // Annotated version (@Smile) is bound to the smile factory.
    bind(ObjectMapper.class).annotatedWith(SmileMapper.class)
            .toProvider(new OpenTableObjectMapperProvider(new SmileFactory())).in(Scopes.SINGLETON);

    // Default (not annotated) instance is bound to json.
    bind(ObjectMapper.class).toProvider(OpenTableObjectMapperProvider.class).in(Scopes.SINGLETON);

    bind(OpenTableJacksonConfig.class).toProvider(ConfigProvider.of(OpenTableJacksonConfig.class))
            .in(Scopes.SINGLETON);

    OpenTableObjectMapperBinder.bindJacksonModule(binder()).toInstance(new GuavaModule());
    OpenTableObjectMapperBinder.bindJacksonModule(binder()).toInstance(new JSR310Module());

    install(new NessCustomSerializerModule());

    // MrBean is pretty safe to globally install, since it only deserializes types that would otherwise fail.
    OpenTableObjectMapperBinder.bindJacksonModule(binder()).to(MrBeanModule.class);

    OpenTableObjectMapperBinder.bindJacksonModule(binder()).to(AfterburnerModule.class);
}

From source file:com.ning.metrics.serialization.event.TestSmileEnvelopeEvent.java

@BeforeTest
public void setUp() throws IOException {
    // Use same configuration as SmileEnvelopeEvent
    final SmileFactory f = new SmileFactory();
    f.configure(SmileGenerator.Feature.CHECK_SHARED_NAMES, true);
    f.configure(SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES, true);
    f.configure(SmileParser.Feature.REQUIRE_HEADER, false);

    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final JsonGenerator g = f.createJsonGenerator(stream);

    g.writeStartObject();//  w w  w  . j  av a 2 s  .co m
    g.writeStringField(SmileEnvelopeEvent.SMILE_EVENT_GRANULARITY_TOKEN_NAME, eventGranularity.toString());
    g.writeObjectFieldStart("name");
    g.writeStringField("first", "Joe");
    g.writeStringField("last", "Sixpack");
    g.writeEndObject(); // for field 'name'
    g.writeStringField("gender", "MALE");
    g.writeNumberField(SmileEnvelopeEvent.SMILE_EVENT_DATETIME_TOKEN_NAME, eventDateTime.getMillis());
    g.writeBooleanField("verified", false);
    g.writeEndObject();
    g.close(); // important: will force flushing of output, close underlying output stream

    serializedBytes = stream.toByteArray();
    // one sanity check; should be able to round-trip via String (iff using latin-1!)
    serializedString = stream.toString(SmileEnvelopeEvent.CHARSET.toString());
}

From source file:io.druid.data.input.impl.SqlFirehoseTest.java

@Before
public void setup() throws IOException {
    TEST_DIR = File.createTempFile(SqlFirehose.class.getSimpleName(), "testDir");
    FileUtils.forceDelete(TEST_DIR);/*from  ww  w . jav a 2s  .  com*/
    FileUtils.forceMkdir(TEST_DIR);

    final List<Map<String, Object>> inputTexts = ImmutableList.of(
            ImmutableMap.of("x", "foostring1", "timestamp", 2000),
            ImmutableMap.of("x", "foostring2", "timestamp", 2000));
    List<FileInputStream> testFile = new ArrayList<>();
    this.objectMapper = new ObjectMapper(new SmileFactory());
    int i = 0;
    for (Map m : inputTexts) {
        File file = new File(TEST_DIR, "test_" + i++);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            final JsonGenerator jg = objectMapper.getFactory().createGenerator(fos);
            jg.writeStartArray();
            jg.writeObject(m);
            jg.writeEndArray();
            jg.close();
            testFile.add(new FileInputStream(file));
        }
    }

    this.fileList = testFile;
    parser = new MapInputRowParser(new TimeAndDimsParseSpec(new TimestampSpec("timestamp", "auto", null),
            new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("x")), null, null)));

    this.inputs = inputTexts;
}

From source file:com.proofpoint.jaxrs.SmileMapper.java

@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream inputStream) throws IOException {
    Object object;//from w  w w . java2 s .  c  om
    try {
        JsonParser jsonParser = new SmileFactory().createParser(inputStream);

        // Important: we are NOT to close the underlying stream after
        // mapping, so we need to instruct parser:
        jsonParser.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);

        object = objectMapper.readValue(jsonParser, objectMapper.getTypeFactory().constructType(genericType));
    } catch (Exception e) {
        // we want to return a 400 for bad JSON but not for a real IO exception
        if (e instanceof IOException && !(e instanceof JsonProcessingException)
                && !(e instanceof EOFException)) {
            throw (IOException) e;
        }

        // log the exception at debug so it can be viewed during development
        // Note: we are not logging at a higher level because this could cause a denial of service
        log.debug(e, "Invalid json for Java type %s", type);

        // Invalid json request. Throwing exception so the response code can be overridden using a mapper.
        throw new JsonMapperParsingException(type, e);
    }

    // validate object using the bean validation framework
    validateObject(genericType, object);

    return object;
}

From source file:com.proofpoint.http.client.SmileResponseHandler.java

@Override
public T handle(Request request, Response response) {
    if (!successfulResponseCodes.contains(response.getStatusCode())) {
        throw new UnexpectedResponseException(String.format("Expected response code to be %s, but was %d: %s",
                successfulResponseCodes, response.getStatusCode(), response.getStatusMessage()), request,
                response);// ww  w .  ja v  a 2  s.  c  o m
    }
    String contentType = response.getHeader(CONTENT_TYPE);
    if (contentType == null) {
        throw new UnexpectedResponseException("Content-Type is not set for response", request, response);
    }
    if (!MediaType.parse(contentType).is(MEDIA_TYPE_SMILE)) {
        throw new UnexpectedResponseException(
                "Expected application/x-jackson-smile response from server but got " + contentType, request,
                response);
    }
    try {
        JsonParser jsonParser = new SmileFactory().createParser(response.getInputStream());
        ObjectMapper objectMapper = OBJECT_MAPPER_SUPPLIER.get();

        // Important: we are NOT to close the underlying stream after
        // mapping, so we need to instruct parser:
        jsonParser.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);

        return objectMapper.readValue(jsonParser,
                objectMapper.getTypeFactory().constructType(jsonCodec.getType()));
    } catch (InvalidFormatException e) {
        throw new IllegalArgumentException("Unable to create " + jsonCodec.getType() + " from SMILE response",
                e);
    } catch (IOException e) {
        throw new RuntimeException("Error reading SMILE response from server", e);
    }
}