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:org.springframework.restdocs.operation.preprocess.PrettyPrintingContentModifierTests.java

@Test
public void encodingIsPreserved() throws Exception {
    Map<String, String> input = new HashMap<>();
    input.put("japanese", "\u30b3\u30f3\u30c6\u30f3\u30c4");
    ObjectMapper objectMapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
    Map<String, String> output = objectMapper.readValue(
            new PrettyPrintingContentModifier().modifyContent(objectMapper.writeValueAsBytes(input), null),
            Map.class);
    assertThat(output, is(equalTo(input)));
}

From source file:org.opentestsystem.shared.docs.RequestLoggingInterceptor.java

@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) throws Exception { // NOPMD
    FileOutputStream fileOut = null;
    try {//from  w  w w.ja v  a2  s  .co m
        LOGGER.debug(" ");
        LOGGER.debug(" ");

        LOGGER.debug("Request ");

        int rank = getRankOfApiDoc();
        // if rank is -1 skip it: that's the way to hide a api doc. Also exclude negative security testing
        if (rank >= ZERO && response.getStatus() != HttpStatus.SC_UNAUTHORIZED) {
            // block pmd concurrent hashmap warning
            ApiExample example = new ApiExample();
            example.setApiDocRank(rank);
            example.setRequestMethod(HttpMethod.valueOf(request.getMethod()));
            example.setRequestContentType(request.getContentType());
            example.setRequestUri(request.getRequestURI());
            String reqQueryString = request.getQueryString();
            //grab the parameters off the request instead
            if (StringUtils.isBlank(reqQueryString)) {
                if (request.getParameterMap() != null) {
                    List<String> params = new ArrayList<String>();
                    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                        String temp = entry.getKey() + "=";
                        if (entry.getValue() != null) {
                            temp += Joiner.on(",").join(entry.getValue());
                        }
                        params.add(temp);
                    }
                    reqQueryString = Joiner.on("&").join(params.toArray());
                }
            }
            example.setRequestQueryString(reqQueryString);

            LOGGER.debug(example.toString());

            InputStream instream = request.getInputStream();
            String requestData = "";
            if (instream != null) {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                requestData = writer.toString();
            }
            example.setRequestData(requestData);
            LOGGER.debug("request data :" + example.getRequestData());
            LOGGER.debug(" ");

            LOGGER.debug("Response  ");
            MockHttpServletResponse res = (MockHttpServletResponse) response;
            example.setResponseContent(res.getContentAsString());
            example.setResponseCode(res.getStatus());

            LOGGER.debug("Server Response:" + example.getResponseContent());
            LOGGER.debug(" ");
            LOGGER.debug(" ");

            if (API_EXAMPLE_FILE != null) {
                fileOut = new FileOutputStream(API_EXAMPLE_FILE, true);
                ObjectMapper mapper = new ObjectMapper();
                byte[] bytes = mapper.writeValueAsBytes(example);
                fileOut.write(bytes);
                String str = ",";
                fileOut.write(str.getBytes());
                fileOut.close();
            }
        }
    } finally {
        if (fileOut != null) {
            fileOut.close();
        }
    }
}

From source file:com.batchiq.nifi.executescript.samples.TestJavascriptSamples.java

/**
 * Demonstrates transforming the JSON object in an incoming FlowFile to output
 * @throws Exception/*from  w  ww  .  j  av a 2  s. c om*/
 */
@Test
public void testTransform() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new ExecuteScript());
    runner.setValidateExpressionUsage(false);
    runner.setProperty(ExecuteScript.SCRIPT_ENGINE, "ECMAScript");
    runner.setProperty(ExecuteScript.SCRIPT_FILE, "target/test/resources/javascript/transform.js");
    runner.setProperty(ExecuteScript.MODULES, "target/test/resources/javascript");
    runner.assertValid();

    InputObject inputJsonObject = new InputObject();
    inputJsonObject.value = 3;
    ObjectMapper mapper = new ObjectMapper();
    byte[] jsonBytes = mapper.writeValueAsBytes(inputJsonObject);

    runner.enqueue(jsonBytes);
    runner.run();

    runner.assertAllFlowFilesTransferred("success", 1);
    final List<MockFlowFile> successFlowFiles = runner.getFlowFilesForRelationship("success");
    MockFlowFile result = successFlowFiles.get(0);
    byte[] flowFileBytes = result.toByteArray();

    OutputObject outputJsonObject = mapper.readValue(flowFileBytes, OutputObject.class);
    Assert.assertEquals(9, outputJsonObject.value);
    Assert.assertEquals("Hello", outputJsonObject.message);
}

From source file:com.batchiq.nifi.executescript.samples.TestPythonSamples.java

/**
 * Demonstrates transforming the JSON object in an incoming FlowFile to output
 * @throws Exception//from w ww  .  j a  v  a  2 s. c om
 */
@Test
public void testTransform() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new ExecuteScript());
    runner.setValidateExpressionUsage(false);
    runner.setProperty(ExecuteScript.SCRIPT_ENGINE, "python");
    runner.setProperty(ExecuteScript.SCRIPT_FILE, "target/test/resources/python/transform.py");
    runner.setProperty(ExecuteScript.MODULES, "target/test/resources/python");
    runner.assertValid();

    InputObject inputJsonObject = new InputObject();
    inputJsonObject.value = 3;
    ObjectMapper mapper = new ObjectMapper();
    byte[] jsonBytes = mapper.writeValueAsBytes(inputJsonObject);

    runner.enqueue(jsonBytes);
    runner.run();

    runner.assertAllFlowFilesTransferred("success", 1);
    final List<MockFlowFile> successFlowFiles = runner.getFlowFilesForRelationship("success");
    MockFlowFile result = successFlowFiles.get(0);
    byte[] flowFileBytes = result.toByteArray();

    OutputObject outputJsonObject = mapper.readValue(flowFileBytes, OutputObject.class);
    Assert.assertEquals(9, outputJsonObject.value);
    Assert.assertEquals("Hello", outputJsonObject.message);
}

From source file:com.metamx.datatypes.mmx.WriteNewLinesTest.java

@Test
public void testSimpleDeserialization() throws Exception {
    List<MmxAuctionSummary> auctionList = Arrays.asList(sampleAuction1, sampleAuction2);
    final String separator = "\n";

    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    final OutputStream outStream = new ByteArrayOutputStream();

    for (MmxAuctionSummary auction : auctionList) {
        outStream.write(objectMapper.writeValueAsBytes(auction));
        outStream.write(separator.getBytes());
    }//ww  w . j ava2s.  co m

    Assert.assertEquals(outputString, outStream.toString());
}

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

/**
 * Commit the checkpoint sequence number for a shard to Zookeeper.
 *
 * @param  shardId  shard to commit to./*from  www .  ja  v a  2 s.co  m*/
 * @param  seqNum  sequence number to commit.
 * @throws Exception
 */
void commitSeqNum(final String shardId, final String seqNum) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    byte[] data = objectMapper.writeValueAsBytes(new ShardStateV0(seqNum));
    NodeFunction commit = NodeFunction.constant(data);
    atomicUpdate(shardId + "/" + STATE_SUFFIX, commit);
}

From source file:net.acesinc.nifi.processors.json.BetterAttributesToJSON.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    final ComponentLog logger = getLogger();
    final FlowFile original = session.get();
    if (original == null) {
        return;/*from  ww  w .  ja  va  2s  .  c  o  m*/
    }
    try {
        final Map<String, Object> attrsToUpdate = buildAttributesMapAndBringInFlowAttrs(original,
                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());

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

@Test
public void serializeEmptyFCCbor() throws JsonProcessingException {
    FeatureCollection fc = new FeatureCollection();
    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) 0xff, // end content map
            (byte) 0xff, // end array
    };/*  w  w w . ja  v  a2  s  . c  o m*/
    assertThat(cbor, is(equalTo(ref)));
}

From source file:org.jboss.pnc.buildagent.client.BuildAgentClient.java

private ByteBuffer prepareRemoteCommand(Object command) throws BuildAgentClientException {
    Map<String, Object> cmdJson = new HashMap<>();
    cmdJson.put("action", "read");

    ByteBuffer byteBuffer;/*from   w w  w .  j  ava 2 s  . co  m*/
    if (command instanceof String) {
        cmdJson.put("data", command + "\n");
        ObjectMapper mapper = new ObjectMapper();
        try {
            byteBuffer = ByteBuffer.wrap(mapper.writeValueAsBytes(cmdJson));
        } catch (JsonProcessingException e) {
            throw new BuildAgentClientException("Cannot serialize string command.", e);
        }
    } else {
        try {
            byteBuffer = ByteBuffer.allocate(1).put(((Integer) command).byteValue());
        } catch (BufferOverflowException | ClassCastException e) {
            throw new BuildAgentClientException("Invalid signal.", e);
        }
        byteBuffer.flip();
    }
    return byteBuffer;
}

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

@Test
public void serializeStringCounter() throws JsonProcessingException {
    StringCounter sc = new StringCounter();
    sc.add("a", 1);
    FeatureCollection fc = new FeatureCollection();
    fc.getFeatures().put("sc", sc);

    CBORFactory cborf = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(cborf);
    byte[] cbor = mapper.writeValueAsBytes(fc);
    byte[] ref = { (byte) 0x9f, (byte) 0xbf, 0x61, 0x76, 0x64, 0x66, 0x63, 0x30, 0x31, (byte) 0xff, (byte) 0xbf, // header
            (byte) 0x62, 0x73, 0x63, // string "sc"
            (byte) 0xd9, (byte) 0xd9, (byte) 0xf8, // tag 55080
            (byte) 0xbf, // map of ??? items
            (byte) 0x61, 0x61, // string "a"
            (byte) 0x01, // integer 1
            (byte) 0xff, // end StringCounter map
            (byte) 0xff, (byte) 0xff // footer
    };//from   ww  w  .j a va  2 s. c  o m
    assertThat(cbor, is(equalTo(ref)));
}