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

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

Introduction

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

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:com.cedarsoft.serialization.test.performance.Bson4JacksonTest.java

@Test
public void testMapper() throws Exception {
    ObjectMapper mapper = new ObjectMapper(jsonFactory);

    com.cedarsoft.serialization.test.performance.jaxb.FileType fileType = new com.cedarsoft.serialization.test.performance.jaxb.FileType(
            "Canon Raw", new com.cedarsoft.serialization.test.performance.jaxb.Extension(".", "cr2", true),
            false);//  w w w . j  a  v  a2  s  .  co  m
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    mapper.writeValue(out, fileType);

    Assertions.assertThat(Hex.encodeHexString(out.toByteArray())).describedAs(out.toString()).isEqualTo(
            "0000000008646570656e64656e740000026964000a00000043616e6f6e205261770003657874656e73696f6e00000000000264656c696d6974657200020000002e0002657874656e73696f6e0004000000637232000864656661756c7400010000");
}

From source file:uk.ac.sanger.npg.picard.AlignmentFilterMetric.java

/**
 * //w w w. j av  a2  s  .c  om
 * @param outJson
 */
public void output(File outJson) {

    this.output();

    ObjectMapper mapper = new ObjectMapper();
    try {
        mapper.writeValue(outJson, this);
    } catch (JsonGenerationException ex) {
        log.error(ex);
    } catch (JsonMappingException ex) {
        log.error(ex);
    } catch (IOException ex) {
        log.error(ex);
    }
}

From source file:cn.powerdash.libsystem.common.security.authc.SessionTimeoutAuthenticationFilter.java

@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response)
        throws IOException {
    saveRequest(request);/*from  w w w .j a  v a2 s.c om*/
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (WebUtil.isAjaxRequest(req)) {
        ObjectMapper objectMapper = new ObjectMapper();
        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        ResultDto<String> error = new ResultDto<String>();
        error.setCode(ResultCode.SESSION_TIME_OUT);
        error.setMessage(MessageUtil.getMessage(SESSION_TIMEOUT_MSG));
        objectMapper.writeValue(response.getWriter(), error);
        LOGGER.debug("session time out for ajax request:{}", req.getRequestURI());
    } else {
        LOGGER.debug("session time out for request:{}", req.getRequestURI());
        req.getSession().setAttribute(SESSION_TIMEOUT, true);
        redirectToLogin(request, response);
    }
    HttpSession session = req.getSession(false);
    if (session != null) {
        LOGGER.debug(
                "session time out with id: {}, is sesion new:{}, started: {}, last accessed: {}, request headers: {}",
                session.getId(), session.isNew(),
                DateFormatUtils.format(session.getCreationTime(), DATE_FORMAT),
                DateFormatUtils.format(session.getLastAccessedTime(), DATE_FORMAT), getHeaderString(request));
    } else {
        LOGGER.debug("session time out, no session available for current request");
    }
}

From source file:com.netflix.genie.common.client.TestBaseGenieClient.java

/**
 * Test to make sure if response is successful collection is returned.
 *
 * @throws GenieException             Random issues.
 * @throws ClientException            A http client.
 * @throws IOException                IOException.
 *///from   www  .  j ava 2  s. c  o m
@Test
public void testExecuteRequestSuccessCollection() throws GenieException, ClientException, IOException {
    Mockito.when(this.response.isSuccess()).thenReturn(true);

    final List<Command> commands = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        commands.add(new Command("name" + i, "user" + i, CommandStatus.ACTIVE, "executable" + i, "" + i));
    }

    final ObjectMapper mapper = new ObjectMapper();
    final StringWriter writer = new StringWriter();
    mapper.writeValue(writer, commands);
    final String inputEntity = writer.toString();
    final InputStream is = new ByteArrayInputStream(inputEntity.getBytes(Charset.forName("UTF-8")));
    Mockito.when(this.response.getInputStream()).thenReturn(is);
    Mockito.when(this.restClient.executeWithLoadBalancer(this.request)).thenReturn(this.response);

    @SuppressWarnings("unchecked")
    final List<Command> outputCommands = (List<Command>) this.client.executeRequest(this.request, List.class,
            Command.class);

    Assert.assertEquals(commands.size(), outputCommands.size());
    for (int i = 0; i < commands.size(); i++) {
        final Command expected = commands.get(i);
        final Command actual = outputCommands.get(i);
        Assert.assertEquals(expected.getName(), actual.getName());
        Assert.assertEquals(expected.getUser(), actual.getUser());
        Assert.assertEquals(expected.getStatus(), actual.getStatus());
        Assert.assertEquals(expected.getExecutable(), actual.getExecutable());
        Assert.assertEquals(expected.getVersion(), actual.getVersion());
    }

    Mockito.verify(this.response, Mockito.times(1)).isSuccess();
    Mockito.verify(this.response, Mockito.times(1)).getInputStream();
}

From source file:com.microsoft.azure.management.resources.core.MockIntegrationTestBase.java

/**
 * Resets the test with name @testName.//from  w  w w . j  a  v a  2  s  .c om
 * This reset call is only valid for tests setup earlier with the same testName.
 * @param testName
 * @throws Exception
 */
protected void resetTest(String testName) throws Exception {
    if (!currentTestName.equals(testName)) {
        return;
    }

    if (IS_RECORD) {
        // Write current context to file
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        File recordFile = getRecordFile();
        recordFile.createNewFile();
        mapper.writeValue(recordFile, testRecord);
    }

    wireMock.resetMappings();
    testRecord = null;
    currentTestName = null;
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * POST?//from w w w.  j a  v a 2s. c  o m
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId == null || targetId.isEmpty()) {
            // POST(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // ?
            LinkedHashMap<String, Object> resultObject = op.createUserInfo(context, request, attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_CREATED);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * PUT?//from   ww w .j  a  v a2s . c o  m
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId != null && !targetId.isEmpty()) {
            // PUT(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // 
            LinkedHashMap<String, Object> resultObject = op.updateUserInfo(context, request, targetId,
                    attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:com.exalttech.trex.util.TrafficProfile.java

/**
 * @param trafficProfileArray/*from ww w  .j a va2  s  .co m*/
 * @param fileName
 *
 * @return Converts Traffic Profile to Yaml String
 * @throws JsonProcessingException
 *
 */
public File convertTrafficProfileToYamlFile(Profile[] trafficProfileArray, String fileName) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    String localFileName = FileManager.getProfilesFilePath() + fileName;
    File yamlFile = new File(localFileName);
    mapper.writeValue(yamlFile, trafficProfileArray);
    return yamlFile;
}

From source file:org.wisdom.monitor.extensions.jcr.script.JcrScriptExecutorExtension.java

public String listToJsonString(List list) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Event.class, new JcrEventSerializer()); // assuming serializer declares correct class to bind to
    mapper.registerModule(module);/*from  w  ww. ja  va2s  . com*/
    mapper.writeValue(out, list);
    final byte[] data = out.toByteArray();
    return new String(data);
}

From source file:org.fusesource.restygwt.server.basic.EchoTestGwtServlet.java

@SuppressWarnings("unchecked")
private void doEchoRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Echo echo = new Echo();
    echo.path = request.getPathInfo();//from   w  ww .ja  va 2  s . c om

    echo.params = new HashMap<String, String>();
    ObjectMapper mapper = new ObjectMapper();
    for (Map.Entry<String, String[]> entry : (Set<Map.Entry<String, String[]>>) request.getParameterMap()
            .entrySet()) {
        if (entry.getValue().length == 1) {
            echo.params.put(entry.getKey(), entry.getValue()[0]);
        } else {
            echo.params.put(entry.getKey(), mapper.writeValueAsString(entry.getValue()));
        }
    }
    response.setContentType("application/json");
    mapper.writeValue(response.getOutputStream(), echo);
}