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:com.diffeo.dossier.fc.FeatureCollectionTest.java

@Test
public void serializeStringFeature() throws JsonProcessingException {
    StringFeature sf = new StringFeature("foo");
    FeatureCollection fc = new FeatureCollection();
    fc.getFeatures().put("f", sf);

    CBORFactory cborf = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(cborf);
    byte[] cbor = mapper.writeValueAsBytes(fc);
    byte[] ref = { (byte) 0x9f, // array of ??? items
            (byte) 0xbf, // map of ??? items
            (byte) 0x61, 0x76, // string "v"
            (byte) 0x64, 0x66, 0x63, 0x30, 0x31, // string "fc01"
            (byte) 0xff, // end metadata map
            (byte) 0xbf, // map of ??? items
            (byte) 0x61, 0x66, // string "f"
            (byte) 0x63, 0x66, 0x6f, 0x6f, // string "foo"
            (byte) 0xff, // end content map
            (byte) 0xff, // end array
    };/*w  ww. ja  va  2  s.  c om*/
    assertThat(cbor, is(equalTo(ref)));
}

From source file:com.amazonaws.services.kinesis.stormspout.state.zookeeper.ZookeeperShardState.java

/**
 * Initialize the shardList in ZK. This is called by every spout task on activate(), and ensures
 * that the shardList is up to date and correct.
 *
 * @param shards  list of shards (output of DescribeStream).
 * @throws Exception/*  w  w w. j a  v a2s  .  c o m*/
 */
void initialize(final ImmutableList<String> shards) throws Exception {
    NodeFunction verifyOrCreateShardList = new NodeFunction() {
        @Override
        public byte[] initialize() {
            LOG.info(this + " First initialization of shardList: " + shards);
            ShardListV0 shardList = new ShardListV0(shards);
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] data;
            try {
                data = objectMapper.writeValueAsBytes(shardList);
            } catch (JsonProcessingException e) {
                throw new KinesisSpoutException("Unable to serialize shardList " + shardList, e);
            }
            return data;
        }

        @Override
        public Mod<byte[]> apply(byte[] x) {
            // At this point, we don't support resharding. We assume the shard list is valid if one exists.
            LOG.info("ShardList already initialized in Zookeeper. Assuming it is valid.");
            return Mod.noModification();
        }
    };

    atomicUpdate(SHARD_LIST_SUFFIX, verifyOrCreateShardList);
}

From source file:org.primeframework.mvc.test.RequestBuilder.java

/**
 * Uses the given object as the JSON body for the request. This object is converted into JSON using Jackson.
 *
 * @param object The object to send in the request.
 * @return This.//from  w ww  .  j  a  v a 2s .com
 * @throws JsonProcessingException If the Jackson marshalling failed.
 */
public RequestBuilder withJSON(Object object) throws JsonProcessingException {
    ObjectMapper objectMapper = injector.getInstance(ObjectMapper.class);
    byte[] json = objectMapper.writeValueAsBytes(object);
    return withContentType("application/json").withBody(json);
}

From source file:net.acesinc.nifi.processors.security.ConvertSecurityMarkingAndAttrListIntoJson.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    final ComponentLog logger = getLogger();
    final FlowFile original = session.get();
    if (original == null) {
        return;/*w  w  w  .jav  a 2 s .co  m*/
    }
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        FlowAttrSecurityConfig secConfig = objectMapper
                .readValue(context.getProperty(CONVERTER_CONFIG).getValue(), FlowAttrSecurityConfig.class);
        final Map<String, Object> attrsToUpdate = buildSecurityAttributesMapForFlowFileAndBringInFlowAttrs(
                original,
                context.getProperty(RAW_SECURITY_MARKING_FROM_FILE_NAME).evaluateAttributeExpressions(original)
                        .getValue(),
                context.getProperty(STRING_ATTRIBUTES_LIST).getValue(),
                context.getProperty(INT_ATTRIBUTES_LIST).getValue(),
                context.getProperty(DOUBLE_ATTRIBUTES_LIST).getValue(),
                context.getProperty(EPOCH_TO_DATES_ATTRIBUTES_LIST).getValue(), secConfig);

        FlowFile conFlowfile = session.write(original, new StreamCallback() {
            @Override
            public void process(InputStream in, OutputStream out) throws IOException {
                try (OutputStream outputStream = new BufferedOutputStream(out)) {
                    ObjectMapper objMapper = new ObjectMapper();
                    outputStream.write(objMapper.writeValueAsBytes(attrsToUpdate));
                }
            }
        });
        conFlowfile = session.putAttribute(conFlowfile, CoreAttributes.MIME_TYPE.key(), APPLICATION_JSON);
        session.transfer(conFlowfile, REL_SUCCESS);

    } catch (IOException ioe) {
        logger.error(ioe.getMessage());
        session.transfer(original, REL_FAILURE);
    }
}

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

@Override
public void write(MessagePacker packer) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());

    // Pack basic information
    packer.packMapHeader(4).packString("type").packString(TYPE).packString("your_cookie")
            .packBinaryHeader(this.yourCookie.length).writePayload(this.yourCookie);

    // Pack tasks list
    packer.packString("tasks").packArrayHeader(this.tasks.size());
    for (String task : this.tasks) {
        packer.packString(task);//w w  w .j  ava  2 s  .c  o m
    }

    // Pack data
    final byte[] dataBytes = objectMapper.writeValueAsBytes(this.data);
    packer.packString("data").writePayload(dataBytes);
}

From source file:io.druid.server.AsyncQueryForwardingServlet.java

@Override
protected void sendProxyRequest(HttpServletRequest clientRequest, HttpServletResponse proxyResponse,
        Request proxyRequest) {/*from   w  ww.j  av  a  2 s.co  m*/
    proxyRequest.timeout(httpClientConfig.getReadTimeout().getMillis(), TimeUnit.MILLISECONDS);
    proxyRequest.idleTimeout(httpClientConfig.getReadTimeout().getMillis(), TimeUnit.MILLISECONDS);

    byte[] avaticaQuery = (byte[]) clientRequest.getAttribute(AVATICA_QUERY_ATTRIBUTE);
    if (avaticaQuery != null) {
        proxyRequest.content(new BytesContentProvider(avaticaQuery));
    }

    final Query query = (Query) clientRequest.getAttribute(QUERY_ATTRIBUTE);
    if (query != null) {
        final ObjectMapper objectMapper = (ObjectMapper) clientRequest.getAttribute(OBJECTMAPPER_ATTRIBUTE);
        try {
            proxyRequest.content(new BytesContentProvider(objectMapper.writeValueAsBytes(query)));
        } catch (JsonProcessingException e) {
            Throwables.propagate(e);
        }
    }

    // Since we can't see the request object on the remote side, we can't check whether the remote side actually
    // performed an authorization check here, so always set this to true for the proxy servlet.
    // If the remote node failed to perform an authorization check, PreResponseAuthorizationCheckFilter
    // will log that on the remote node.
    clientRequest.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);

    // Check if there is an authentication result and use it to decorate the proxy request if needed.
    AuthenticationResult authenticationResult = (AuthenticationResult) clientRequest
            .getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT);
    if (authenticationResult != null && authenticationResult.getAuthenticatedBy() != null) {
        Authenticator authenticator = authenticatorMapper.getAuthenticatorMap()
                .get(authenticationResult.getAuthenticatedBy());
        if (authenticator != null) {
            authenticator.decorateProxyRequest(clientRequest, proxyResponse, proxyRequest);
        } else {
            log.error("Can not find Authenticator with Name [%s]", authenticationResult.getAuthenticatedBy());
        }
    }
    super.sendProxyRequest(clientRequest, proxyResponse, proxyRequest);
}

From source file:org.forgerock.openicf.connectors.elastic.ElasticConnector.java

private byte[] attributesToBytes(Set<Attribute> attributes) {
    try {/*from   w ww  .j a v  a 2s .co  m*/
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode objectNode = mapper.createObjectNode();
        for (Attribute attr : attributes) {
            final List<Object> value = attr.getValue();
            objectNode.putPOJO(attr.getName(),
                    value != null && value.size() > 1 ? value : AttributeUtil.getSingleValue(attr));
        }
        return mapper.writeValueAsBytes(objectNode);
    } catch (JsonProcessingException e) {
        logger.error(e, null);
        return new byte[0];
    }
}

From source file:com.ge.predix.uaa.token.lib.FastTokenServiceTest.java

/**
 * Tests that a tampered token issues an InvalidTokenException.
 *//*from   ww w.jav a  2s.c o m*/
@Test(expectedExceptions = InvalidSignatureException.class)
public void testLoadAuthenticationWithTamperedToken() throws Exception {
    String accessToken = this.testTokenUtil.mockAccessToken(60);

    // Start tamper ;)
    String[] jwtParts = accessToken.split("\\.");
    String jwtHeader = jwtParts[0];
    String jwtContent = jwtParts[1];
    String jwtSignature = jwtParts[2];

    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<Map<String, Object>> valueTypeRef = new TypeReference<Map<String, Object>>() {
        // Nothing to declare.
    };
    String decodedClaims = new String(Base64.decodeBase64(jwtContent));
    Map<String, Object> claims = objectMapper.readValue(decodedClaims, valueTypeRef);
    claims.put(USER_ID, "admin");
    String encodedClaims = Base64.encodeBase64String(objectMapper.writeValueAsBytes(claims));
    accessToken = jwtHeader + "." + encodedClaims + "." + jwtSignature;

    // We've tampered the token so this should fail.
    this.services.loadAuthentication(accessToken);
}

From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2Ping.java

/**
 * Returns the OpenURLResponse of a JSON object defining image status. Status Codes:
 *///from  ww w.j  av  a  2  s. co m
@Override
public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject,
        final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) {
    final String responseFormat = RESPONSE_TYPE;
    int status = HttpServletResponse.SC_NOT_FOUND;
    byte[] bytes = new byte[] {};

    try {
        final String id = ((URI) contextObject.getReferent().getDescriptors()[0]).toASCIIString();
        status = ReferentManager.getResolver().getStatus(id);

        if (status != HttpServletResponse.SC_NOT_FOUND) {
            final ObjectMapper mapper = new ObjectMapper();
            final ObjectNode rootNode = mapper.createObjectNode();

            String res_status = null;

            if (status == HttpServletResponse.SC_OK) {
                res_status = STATUS_OK;
            } else if (status == HttpServletResponse.SC_ACCEPTED) {
                res_status = STATUS_ACCEPTED;
            }

            rootNode.put("identifier", id);
            rootNode.put("status", res_status);
            bytes = mapper.writeValueAsBytes(rootNode);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    final HashMap<String, String> header_map = new HashMap<String, String>();
    header_map.put("Content-Length", Integer.toString(bytes.length));
    header_map.put("Date", HttpDate.getHttpDate());
    return new OpenURLResponse(status, responseFormat, bytes, header_map);
}

From source file:com.sothawo.taboo2.Taboo2ServiceTests.java

private byte[] convertObjectToJsonBytes(Object o) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.writeValueAsBytes(o);
}