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

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

Introduction

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

Prototype

@SuppressWarnings("resource")
public String writeValueAsString(Object value) throws JsonProcessingException 

Source Link

Document

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

Usage

From source file:com.spotify.helios.common.descriptors.JobTest.java

private static void removeFieldAndParse(final Job job, final String... fieldNames) throws Exception {
    final String jobJson = job.toJsonString();

    final ObjectMapper objectMapper = new ObjectMapper();
    final Map<String, Object> fields = objectMapper.readValue(jobJson,
            new TypeReference<Map<String, Object>>() {
            });/*from  w w  w.j  ava  2s  .  c om*/

    for (final String field : fieldNames) {
        fields.remove(field);
    }
    final String modifiedJobJson = objectMapper.writeValueAsString(fields);

    final Job parsedJob = parse(modifiedJobJson, Job.class);

    assertEquals(job, parsedJob);
}

From source file:com.sugaronrest.restapicalls.methodcalls.GetLinkedEntry.java

/**
 * Gets linked entry[SugarCRM REST method - get_entry].
 *
 * @param url REST API Url./*from www. j  av  a 2s.  c o m*/
 * @param sessionId Session identifier.
 * @param moduleName SugarCRM module name.
 * @param identifier The entity identifier.
 * @param selectFields Selected field list.
 * @param linkedSelectFields Linked field info.
 * @return ReadLinkedEntryResponse object
 */
public static ReadLinkedEntryResponse run(String url, String sessionId, String moduleName, String identifier,
        List<String> selectFields, List<Object> linkedSelectFields) {

    ReadLinkedEntryResponse readLinkedEntryResponse = null;
    ErrorResponse errorResponse = null;

    String jsonRequest = new String();
    String jsonResponse = new String();

    ObjectMapper mapper = JsonObjectMapper.getMapper();

    try {
        Map<String, Object> requestData = new LinkedHashMap<String, Object>();
        requestData.put("session", sessionId);
        requestData.put("module_name", moduleName);
        requestData.put("id", identifier);
        requestData.put("select_fields", selectFields);
        boolean linkedInfoNotSet = ((linkedSelectFields == null) || (linkedSelectFields.size() == 0));
        requestData.put("link_name_to_fields_array", linkedInfoNotSet ? StringUtils.EMPTY : linkedSelectFields);
        requestData.put("track_view", false);

        String jsonRequestData = mapper.writeValueAsString(requestData);

        Map<String, Object> request = new LinkedHashMap<String, Object>();
        request.put("method", "get_entry");
        request.put("input_type", "json");
        request.put("response_type", "json");
        request.put("rest_data", requestData);

        jsonRequest = mapper.writeValueAsString(request);

        request.put("rest_data", jsonRequestData);

        HttpResponse response = Unirest.post(url).fields(request).asString();

        if (response == null) {
            readLinkedEntryResponse = new ReadLinkedEntryResponse();
            errorResponse = ErrorResponse.format("An error has occurred!", "No data returned.");
            readLinkedEntryResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            readLinkedEntryResponse.setError(errorResponse);
        } else {

            jsonResponse = response.getBody().toString();

            if (StringUtils.isNotBlank(jsonResponse)) {
                // First check if we have an error
                errorResponse = ErrorResponse.fromJson(jsonResponse);
                if (errorResponse == null) {
                    readLinkedEntryResponse = mapper.readValue(jsonResponse, ReadLinkedEntryResponse.class);
                }
            }

            if (readLinkedEntryResponse == null) {
                readLinkedEntryResponse = new ReadLinkedEntryResponse();
                readLinkedEntryResponse.setError(errorResponse);

                readLinkedEntryResponse.setStatusCode(HttpStatus.SC_OK);
                if (errorResponse != null) {
                    readLinkedEntryResponse.setStatusCode(errorResponse.getStatusCode());
                }
            } else {
                readLinkedEntryResponse.setStatusCode(HttpStatus.SC_OK);
            }
        }
    } catch (Exception exception) {
        readLinkedEntryResponse = new ReadLinkedEntryResponse();
        errorResponse = ErrorResponse.format(exception, exception.getMessage());
        readLinkedEntryResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        errorResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        readLinkedEntryResponse.setError(errorResponse);
    }

    readLinkedEntryResponse.setJsonRawRequest(jsonRequest);
    readLinkedEntryResponse.setJsonRawResponse(jsonResponse);

    return readLinkedEntryResponse;
}

From source file:com.sugaronrest.restapicalls.methodcalls.GetEntryList.java

/**
 * Gets entries [SugarCRM REST method - get_entry_list].
 *
 * @param url REST API Url./*from ww  w  .j av  a  2  s . com*/
 * @param sessionId Session identifier.
 * @param moduleName SugarCRM module name.
 * @param selectFields Selected field list.
 * @param queryString Formatted query string.
 * @param maxCountResult Maximum number of entries to return.
 * @return ReadEntryListResponse object.
 * @throws Exception
 */
public static ReadEntryListResponse run(String url, String sessionId, String moduleName,
        List<String> selectFields, String queryString, int maxCountResult) throws Exception {

    ReadEntryListResponse readEntryListResponse = null;
    ErrorResponse errorResponse = null;

    String jsonRequest = new String();
    String jsonResponse = new String();

    ObjectMapper mapper = JsonObjectMapper.getMapper();

    try {
        Map<String, Object> requestData = new LinkedHashMap<String, Object>();
        requestData.put("session", sessionId);
        requestData.put("module_name", moduleName);
        requestData.put("query", queryString);
        requestData.put("order_by", StringUtils.EMPTY);
        requestData.put("offset", 0);
        requestData.put("select_fields", selectFields);
        requestData.put("link_name_to_fields_array", StringUtils.EMPTY);
        requestData.put("max_results", maxCountResult);
        requestData.put("deleted", 0);
        requestData.put("favorites", false);

        String jsonRequestData = mapper.writeValueAsString(requestData);

        Map<String, Object> request = new LinkedHashMap<String, Object>();
        request.put("method", "get_entry_list");
        request.put("input_type", "json");
        request.put("response_type", "json");
        request.put("rest_data", requestData);

        jsonRequest = mapper.writeValueAsString(request);

        request.put("rest_data", jsonRequestData);

        HttpResponse response = Unirest.post(url).fields(request).asJson();

        if (response == null) {
            readEntryListResponse = new ReadEntryListResponse();
            errorResponse = ErrorResponse.format("An error has occurred!", "No data returned.");
            readEntryListResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            readEntryListResponse.setError(errorResponse);
        } else {

            jsonResponse = response.getBody().toString();

            if (StringUtils.isNotBlank(jsonResponse)) {
                // First check if we have an error
                errorResponse = ErrorResponse.fromJson(jsonResponse);
                if (errorResponse == null) {
                    readEntryListResponse = mapper.readValue(jsonResponse, ReadEntryListResponse.class);
                }
            }

            if (readEntryListResponse == null) {
                readEntryListResponse = new ReadEntryListResponse();
                readEntryListResponse.setError(errorResponse);

                readEntryListResponse.setStatusCode(HttpStatus.SC_OK);
                if (errorResponse != null) {
                    readEntryListResponse.setStatusCode(errorResponse.getStatusCode());
                }
            } else {
                readEntryListResponse.setStatusCode(HttpStatus.SC_OK);
            }
        }
    } catch (Exception exception) {
        readEntryListResponse = new ReadEntryListResponse();
        errorResponse = ErrorResponse.format(exception, exception.getMessage());
        readEntryListResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        errorResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        readEntryListResponse.setError(errorResponse);
    }

    readEntryListResponse.setJsonRawRequest(jsonRequest);
    readEntryListResponse.setJsonRawResponse(jsonResponse);

    return readEntryListResponse;
}

From source file:at.becast.youploader.database.SQLite.java

public static int addUpload(File file, Video data, VideoMetadata metadata, Date startAt)
        throws SQLException, IOException {
    PreparedStatement prest = null;
    ObjectMapper mapper = new ObjectMapper();
    String sql = "INSERT INTO `uploads` (`account`, `file`, `lenght`, `data`,`enddir`, `metadata`, `status`,`starttime`) "
            + "VALUES (?,?,?,?,?,?,?,?)";
    prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    prest.setInt(1, metadata.getAccount());
    prest.setString(2, file.getAbsolutePath());
    prest.setLong(3, file.length());//from   ww w. j a  v  a2s .c  o m
    prest.setString(4, mapper.writeValueAsString(data));
    prest.setString(5, metadata.getEndDirectory());
    prest.setString(6, mapper.writeValueAsString(metadata));
    prest.setString(7, UploadManager.Status.NOT_STARTED.toString());
    if (startAt == null) {
        prest.setString(8, "");
    } else {
        prest.setDate(8, new java.sql.Date(startAt.getTime()));
    }
    prest.execute();
    ResultSet rs = prest.getGeneratedKeys();
    prest.close();
    if (rs.next()) {
        int id = rs.getInt(1);
        rs.close();
        return id;
    } else {
        return -1;
    }
}

From source file:com.sugaronrest.restapicalls.methodcalls.GetPagedEntryList.java

/**
 * Gets paged entries [SugarCRM REST method - get_entry_list].
 *
 * @param url REST API Url.//  www.  jav a 2s .  co m
 * @param sessionId Session identifier.
 * @param moduleName SugarCRM module name.
 * @param selectFields Selected field list.
 * @param queryString Formatted query string.
 * @param currentPage The current page number.
 * @param numberPerPage The number of pages per page.
 * @return ReadEntryListResponse object.
 * @throws Exception
 */
public static ReadEntryListResponse run(String url, String sessionId, String moduleName,
        List<String> selectFields, String queryString, int currentPage, int numberPerPage) throws Exception {

    ReadEntryListResponse readEntryListResponse = null;
    ErrorResponse errorResponse = null;

    String jsonRequest = new String();
    String jsonResponse = new String();

    ObjectMapper mapper = JsonObjectMapper.getMapper();

    try {
        Map<String, Object> requestData = new LinkedHashMap<String, Object>();
        requestData.put("session", sessionId);
        requestData.put("module_name", moduleName);
        requestData.put("query", queryString);
        requestData.put("order_by", StringUtils.EMPTY);
        int offset = (currentPage - 1) * numberPerPage;
        requestData.put("offset", offset);
        requestData.put("select_fields", selectFields);
        requestData.put("link_name_to_fields_array", StringUtils.EMPTY);
        requestData.put("max_results", numberPerPage);
        requestData.put("deleted", 0);
        requestData.put("favorites", false);

        String jsonRequestData = mapper.writeValueAsString(requestData);

        Map<String, Object> request = new LinkedHashMap<String, Object>();
        request.put("method", "get_entry_list");
        request.put("input_type", "json");
        request.put("response_type", "json");
        request.put("rest_data", requestData);

        jsonRequest = mapper.writeValueAsString(request);

        request.put("rest_data", jsonRequestData);

        HttpResponse response = Unirest.post(url).fields(request).asJson();

        if (response == null) {
            readEntryListResponse = new ReadEntryListResponse();
            errorResponse = ErrorResponse.format("An error has occurred!", "No data returned.");
            readEntryListResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            readEntryListResponse.setError(errorResponse);
        } else {

            jsonResponse = response.getBody().toString();

            if (StringUtils.isNotBlank(jsonResponse)) {
                // First check if we have an error
                errorResponse = ErrorResponse.fromJson(jsonResponse);
                if (errorResponse == null) {
                    readEntryListResponse = mapper.readValue(jsonResponse, ReadEntryListResponse.class);
                }
            }

            if (readEntryListResponse == null) {
                readEntryListResponse = new ReadEntryListResponse();
                readEntryListResponse.setError(errorResponse);

                readEntryListResponse.setStatusCode(HttpStatus.SC_OK);
                if (errorResponse != null) {
                    readEntryListResponse.setStatusCode(errorResponse.getStatusCode());
                }
            } else {
                readEntryListResponse.setStatusCode(HttpStatus.SC_OK);
            }
        }
    } catch (Exception exception) {
        readEntryListResponse = new ReadEntryListResponse();
        errorResponse = ErrorResponse.format(exception, exception.getMessage());
        readEntryListResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        errorResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        readEntryListResponse.setError(errorResponse);
    }

    readEntryListResponse.setJsonRawRequest(jsonRequest);
    readEntryListResponse.setJsonRawResponse(jsonResponse);

    return readEntryListResponse;
}

From source file:nl.knmi.adaguc.services.oauth2.OAuth2Handler.java

/**
 * Sets session parameters for the impactportal
 * //from   w  w  w.j av a 2s  .  c  o  m
 * @param request
 * @param userInfo
 * @throws JSONException
 */
public static void setSessionInfo(HttpServletRequest request, UserInfo userInfo) throws JSONException {
    request.getSession().setAttribute("openid_identifier", userInfo.user_openid);
    request.getSession().setAttribute("user_identifier", userInfo.user_identifier);
    request.getSession().setAttribute("emailaddress", userInfo.user_email);
    request.getSession().setAttribute("certificate", userInfo.certificate);
    request.getSession().setAttribute("oauth_access_token", userInfo.oauth_access_token);
    request.getSession().setAttribute("login_method", "oauth2");

    try {
        makeUserCertificate(User.makePosixUserId(userInfo.user_identifier));
        Token token = TokenManager.registerToken(UserManager.getUser(userInfo.user_identifier));
        ObjectMapper om = new ObjectMapper();
        String result = om.writeValueAsString(token);
        Debug.println(result);
        JSONObject accessToken = new JSONObject(result);
        // accessToken.put("domain",
        // url.substring(0,url.lastIndexOf("/")).replaceAll("https://",
        // ""));
        if (accessToken.has("error")) {
            Debug.errprintln("Error getting user cert: " + accessToken.toString());
            request.getSession().setAttribute("services_access_token", accessToken.toString());
        } else {
            Debug.println("makeUserCertificate succeeded: " + accessToken.toString());
            request.getSession().setAttribute("services_access_token", accessToken.get("token"));
            // request.getSession().setAttribute("backend", MainServicesConfigurator.getServerExternalURL());
            Debug.println("makeUserCertificate succeeded: " + accessToken);
        }

    } catch (Exception e) {
        request.getSession().setAttribute("services_access_token", null);
        Debug.errprintln("makeUserCertificate Failed");
        Debug.printStackTrace(e);
    }
}

From source file:org.ocelotds.integration.AbstractOcelotTest.java

/**
 * Transforme un objet en json, attention aux string
 *
 * @param obj//from  w w  w. jav a2s .  c  o  m
 * @return
 */
protected static String getJson(Object obj) {
    try {
        if (String.class.isInstance(obj)) {
            return Constants.QUOTE + obj + Constants.QUOTE;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(obj);
    } catch (IOException ex) {
        return null;
    }
}

From source file:io.appform.jsonrules.utils.Rule.java

public String representation(ObjectMapper mapper) throws Exception {
    return mapper.writeValueAsString(expression);
}

From source file:com.sugaronrest.restapicalls.methodcalls.GetLinkedEntryList.java

/**
 * Gets linked entries [SugarCRM REST method - get_entry_list].
 *
 * @param url REST API Url.// w w w  . j a  v a  2  s . c o  m
 * @param sessionId Session identifier.
 * @param moduleName SugarCRM module name.
 * @param selectFields Selected field list.
 * @param linkedSelectFields Linked field info.
 * @param queryString Formatted query string.
 * @param maxCountResult Maximum number of entries to return.
 * @return ReadLinkedEntryListResponse object
 * @throws Exception
 */
public static ReadLinkedEntryListResponse run(String url, String sessionId, String moduleName,
        List<String> selectFields, List<Object> linkedSelectFields, String queryString, int maxCountResult)
        throws Exception {

    ReadLinkedEntryListResponse readLinkedEntryListResponse = null;
    ErrorResponse errorResponse = null;

    String jsonRequest = new String();
    String jsonResponse = new String();

    ObjectMapper mapper = JsonObjectMapper.getMapper();

    try {
        Map<String, Object> requestData = new LinkedHashMap<String, Object>();
        requestData.put("session", sessionId);
        requestData.put("module_name", moduleName);
        requestData.put("query", queryString);
        requestData.put("order_by", StringUtils.EMPTY);
        requestData.put("offset", 0);
        requestData.put("select_fields", selectFields);
        boolean linkedInfoNotSet = ((linkedSelectFields == null) || (linkedSelectFields.size() == 0));
        requestData.put("link_name_to_fields_array", linkedInfoNotSet ? StringUtils.EMPTY : linkedSelectFields);
        requestData.put("max_results", maxCountResult);
        requestData.put("deleted", 0);
        requestData.put("favorites", false);

        String jsonRequestData = mapper.writeValueAsString(requestData);

        Map<String, Object> request = new LinkedHashMap<String, Object>();
        request.put("method", "get_entry_list");
        request.put("input_type", "json");
        request.put("response_type", "json");
        request.put("rest_data", requestData);

        jsonRequest = mapper.writeValueAsString(request);

        request.put("rest_data", jsonRequestData);

        HttpResponse response = Unirest.post(url).fields(request).asJson();

        if (response == null) {
            readLinkedEntryListResponse = new ReadLinkedEntryListResponse();
            errorResponse = ErrorResponse.format("An error has occurred!", "No data returned.");
            readLinkedEntryListResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            readLinkedEntryListResponse.setError(errorResponse);
        } else {

            jsonResponse = response.getBody().toString();

            if (StringUtils.isNotBlank(jsonResponse)) {
                // First check if we have an error
                errorResponse = ErrorResponse.fromJson(jsonResponse);
                if (errorResponse == null) {
                    readLinkedEntryListResponse = mapper.readValue(jsonResponse,
                            ReadLinkedEntryListResponse.class);
                }
            }

            if (readLinkedEntryListResponse == null) {
                readLinkedEntryListResponse = new ReadLinkedEntryListResponse();
                readLinkedEntryListResponse.setError(errorResponse);

                readLinkedEntryListResponse.setStatusCode(HttpStatus.SC_OK);
                if (errorResponse != null) {
                    readLinkedEntryListResponse.setStatusCode(errorResponse.getStatusCode());
                }
            } else {
                readLinkedEntryListResponse.setStatusCode(HttpStatus.SC_OK);
            }
        }
    } catch (Exception exception) {
        readLinkedEntryListResponse = new ReadLinkedEntryListResponse();
        errorResponse = ErrorResponse.format(exception, exception.getMessage());
        readLinkedEntryListResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        errorResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        readLinkedEntryListResponse.setError(errorResponse);
    }

    readLinkedEntryListResponse.setJsonRawRequest(jsonRequest);
    readLinkedEntryListResponse.setJsonRawResponse(jsonResponse);

    return readLinkedEntryListResponse;
}

From source file:com.linecorp.bot.model.message.imagemap.MessageImagemapActionTest.java

@Test
public void getText() throws Exception {
    MessageImagemapAction imageMapAction = new MessageImagemapAction("hoge", new ImagemapArea(1, 2, 3, 4));

    ObjectMapper objectMapper = new ObjectMapper();
    String s = objectMapper.writeValueAsString(imageMapAction);
    assertThat(s).contains("\"type\":\"message\"");
}