Example usage for com.fasterxml.jackson.databind ObjectMapper writeValueAsBytes

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValueAsBytes

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writeValueAsBytes.

Prototype

@SuppressWarnings("resource")
public byte[] writeValueAsBytes(Object value) throws JsonProcessingException 

Source Link

Document

Method that can be used to serialize any Java value as a byte array.

Usage

From source file:net.nullschool.grains.jackson.datatype.BasicCollectionsTest.java

@Test
public void test_basicConstSortedMap() throws IOException {
    ConstSortedMap<String, Integer> map = emptySortedMap(null);
    for (int i = 0; i < 5; i++) {
        ObjectMapper mapper = newGrainsObjectMapper();
        byte[] data = mapper.writeValueAsBytes(map);
        ConstSortedMap<?, ?> actual = mapper.readValue(data,
                new TypeReference<ConstSortedMap<String, Integer>>() {
                });/*from   ww  w . j  av a  2  s .c om*/
        CollectionTestingTools.compare_sorted_maps(map, actual);
        map = map.with(String.valueOf(i), i);
    }
}

From source file:com.hp.autonomy.types.idol.content.ScheduleTest.java

@Test
public void json() throws IOException {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    final byte[] json = objectMapper.writeValueAsBytes(schedule);
    assertNotNull(json);//w w w.  j  ava 2s .  co  m
    final Schedule processedSchedule = objectMapper.readValue(json, Schedule.class);
    assertEquals(schedule, processedSchedule);
}

From source file:com.diffeo.dossier.fc.StringCounterTest.java

@Test
public void serializeToCbor() throws JsonProcessingException {
    StringCounter name = new StringCounter();
    name.add("John Smith", 1);

    CBORFactory cborf = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(cborf);
    byte[] cbor = mapper.writeValueAsBytes(name);
    byte[] ref = { (byte) 0xd9, (byte) 0xd9, (byte) 0xf8, // tag 55080
            (byte) 0xbf, // map of ??? items
            (byte) 0x6a, 0x4a, 0x6f, 0x68, 0x6e, 0x20, 0x53, 0x6d, 0x69, 0x74, 0x68, // string "John Smith"
            (byte) 0x01, // integer 1
            (byte) 0xff, // end map
    };/*  w ww  .  j av a 2 s.  co  m*/
    assertThat(cbor, is(equalTo(ref)));
}

From source file:org.saltyrtc.client.messages.c2c.InitiatorAuth.java

@Override
public void write(MessagePacker packer) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    final byte[] dataBytes = objectMapper.writeValueAsBytes(this.data);
    packer.packMapHeader(4).packString("type").packString(TYPE).packString("your_cookie")
            .packBinaryHeader(this.yourCookie.length).writePayload(this.yourCookie).packString("task")
            .packString(this.task).packString("data").writePayload(dataBytes);
}

From source file:hello.MainControllerTest.java

@Test
public void testUpdateSameIds() throws Exception {
    final Todo updatedTodo = new Todo(1L, "z", true);
    ObjectMapper objectMapper = new ObjectMapper();
    byte[] bytes = objectMapper.writeValueAsBytes(updatedTodo);

    when(repository.save(Mockito.any(Todo.class))).thenReturn(updatedTodo);

    mvc.perform(put("/todos/{id}", 1L).contentType(MediaType.APPLICATION_JSON).content(bytes))
            .andExpect(status().isNoContent());

    verify(repository, times(0)).delete(1L);
    verify(repository, times(1)).save(Mockito.any(Todo.class));
    verifyNoMoreInteractions(repository);
}

From source file:hello.MainControllerTest.java

@Test
public void testUpdateDifferentIds() throws Exception {
    final Todo updatedTodo = new Todo(99L, "z", true);
    ObjectMapper objectMapper = new ObjectMapper();
    byte[] bytes = objectMapper.writeValueAsBytes(updatedTodo);

    when(repository.save(Mockito.any(Todo.class))).thenReturn(updatedTodo);

    mvc.perform(put("/todos/{id}", 1L).contentType(MediaType.APPLICATION_JSON).content(bytes))
            .andExpect(status().isNoContent());

    verify(repository, times(1)).delete(1L);
    verify(repository, times(1)).save(Mockito.any(Todo.class));
    verifyNoMoreInteractions(repository);
}

From source file:hello.MainControllerTest.java

@Test
public void testCreate() throws Exception {
    final Todo todo = new Todo(1L, "a", false);
    ObjectMapper objectMapper = new ObjectMapper();
    final byte[] bytes = objectMapper.writeValueAsBytes(todo);

    when(repository.save(Mockito.any(Todo.class))).thenReturn(todo);

    mvc.perform(post("/todos").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
            .content(bytes)).andExpect(status().isOk()).andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.description", is("a"))).andExpect(jsonPath("$.complete", is(false)));

    verify(repository, times(1)).save(Mockito.any(Todo.class));
    verifyNoMoreInteractions(repository);
}

From source file:reactor.io.codec.json.JacksonJsonCodec.java

@Override
protected Function<OUT, byte[]> serializer(final ObjectMapper engine) {
    return new Function<OUT, byte[]>() {
        @Override//ww w.  java 2 s.c  o  m
        public byte[] apply(OUT o) {
            try {
                return engine.writeValueAsBytes(o);
            } catch (JsonProcessingException e) {
                throw new IllegalArgumentException(e.getMessage(), e);
            }
        }
    };
}

From source file:org.cryptomator.crypto.engine.impl.CryptorImpl.java

@Override
public byte[] writeKeysToMasterkeyFile(CharSequence passphrase) {
    final byte[] scryptSalt = new byte[SCRYPT_SALT_LENGTH];
    randomSource.nextBytes(scryptSalt);/*from w w w . java  2s . c  o m*/

    final byte[] kekBytes = Scrypt.scrypt(passphrase, scryptSalt, SCRYPT_COST_PARAM, SCRYPT_BLOCK_SIZE,
            KEYLENGTH_IN_BYTES);
    final byte[] wrappedEncryptionKey;
    final byte[] wrappedMacKey;
    try {
        final SecretKey kek = new SecretKeySpec(kekBytes, ENCRYPTION_ALG);
        wrappedEncryptionKey = AesKeyWrap.wrap(kek, encryptionKey);
        wrappedMacKey = AesKeyWrap.wrap(kek, macKey);
    } finally {
        Arrays.fill(kekBytes, (byte) 0x00);
    }

    final Mac mac = new ThreadLocalMac(macKey, MAC_ALG).get();
    final byte[] versionMac = mac
            .doFinal(ByteBuffer.allocate(Integer.BYTES).putInt(CURRENT_VAULT_VERSION).array());

    final KeyFile keyfile = new KeyFile();
    keyfile.setVersion(CURRENT_VAULT_VERSION);
    keyfile.setScryptSalt(scryptSalt);
    keyfile.setScryptCostParam(SCRYPT_COST_PARAM);
    keyfile.setScryptBlockSize(SCRYPT_BLOCK_SIZE);
    keyfile.setEncryptionMasterKey(wrappedEncryptionKey);
    keyfile.setMacMasterKey(wrappedMacKey);
    keyfile.setVersionMac(versionMac);

    try {
        final ObjectMapper om = new ObjectMapper();
        return om.writeValueAsBytes(keyfile);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException("Unable to create JSON from " + keyfile, e);
    }
}

From source file:com.couchbase.lite.CollationTest.java

public String encode(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    try {//from ww w  . j a  v  a 2  s .  co  m
        byte[] bytes = mapper.writeValueAsBytes(obj);
        String result = new String(bytes);
        return result;
    } catch (Exception e) {
        Log.e(TAG, "Error encoding JSON", e);
        return null;
    }
}