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

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

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectWriter 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:controllers.BundlesController.java

public Result export() {
    final Form<ExportBundleRequest> form = Tools.bindMultiValueFormFromRequest(ExportBundleRequest.class);

    if (form.hasErrors()) {
        BreadcrumbList bc = new BreadcrumbList();
        bc.addCrumb("System", routes.SystemController.index(0));
        bc.addCrumb("Content packs", routes.BundlesController.index());
        bc.addCrumb("Create", routes.BundlesController.exportForm());

        Map<String, List> data = getListData();

        flash("error", "Please correct the fields marked in red to export the bundle");
        return badRequest(views.html.system.bundles.export.render(form, currentUser(), bc,
                (List<Input>) data.get("inputs"), (List<Output>) data.get("outputs"),
                (List<Stream>) data.get("streams"), (List<Dashboard>) data.get("dashboards")));
    }//from  w  ww  . j av a2 s  .  c  om

    try {
        final ExportBundleRequest exportBundleRequest = form.get();
        ConfigurationBundle bundle = bundleService.export(exportBundleRequest);

        response().setContentType(MediaType.JSON_UTF_8.toString());
        response().setHeader("Content-Disposition", "attachment; filename=content_pack.json");
        ObjectMapper m = new ObjectMapper();
        ObjectWriter ow = m.writer().withDefaultPrettyPrinter();
        return ok(ow.writeValueAsString(bundle));
    } catch (IOException e) {
        flash("error", "Could not reach Graylog server");
    } catch (Exception e) {
        flash("error", "Unexpected error exporting configuration bundle, please try again later");
    }

    return redirect(routes.BundlesController.exportForm());
}

From source file:cz.muni.fi.mushroomhunter.restclient.MushroomUpdateSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    DefaultTableModel model = (DefaultTableModel) restClient.getTblMushroom().getModel();
    int selectedRow = restClient.getTblMushroom().getSelectedRow();

    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.ALL);//from   w  ww  .  j a v a  2 s .co m
    headers.setAccept(mediaTypeList);

    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<MushroomDto> responseEntity = restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/mushroom/" + RestClient.getMushroomIDs().get(selectedRow),
            HttpMethod.GET, request, MushroomDto.class);

    MushroomDto mushroomDto = responseEntity.getBody();

    mushroomDto.setName(restClient.getTfMushroomName().getText());

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMMM-yyyy", new Locale("en_US"));

    //to create date object only month is used, day and year are fixed values
    String dateInString = "01-" + restClient.getComboBoxMushroomStartOfOccurence().getSelectedItem().toString()
            + "-2000";
    mushroomDto.setStartOfOccurence(formatter.parse(dateInString));

    //to create date object only month is used, day and year are fixed values
    dateInString = "01-" + restClient.getComboBoxMushroomEndOfOccurence().getSelectedItem().toString()
            + "-2000";
    mushroomDto.setEndOfOccurence(formatter.parse(dateInString));

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(mushroomDto);
    request = new HttpEntity(json, headers);

    restTemplate.exchange(RestClient.SERVER_URL + "pa165/rest/mushroom", HttpMethod.PUT, request,
            MushroomDto.class);
    return selectedRow;
}

From source file:eu.freme.common.persistence.model.OwnedResource.java

public String toJson() throws JsonProcessingException {
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    return ow.writeValueAsString(this);
}

From source file:edu.ucsd.crbs.cws.App.java

License:asdf

public static void getWorkflowAsJson(OptionSet optionSet) throws Exception {
    WorkflowRestDAOImpl workflowDAO = new WorkflowRestDAOImpl();
    workflowDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
    User u = getUserFromOptionSet(optionSet);
    workflowDAO.setUser(u);/*from  w w w .  j a  va2 s . c  om*/

    Long wfid = (Long) optionSet.valueOf(GET_WORKFLOW_ARG);
    Workflow w = workflowDAO.getWorkflowById(wfid.toString(), u);
    if (w != null) {
        ObjectMapper om = new ObjectMapper();
        ObjectWriter ow = om.writerWithDefaultPrettyPrinter();
        System.out.println(ow.writeValueAsString(w));
    } else {
        System.err.println("Unable to retreive WorkspaceFile with id: " + wfid.toString());
        System.exit(1);
    }
}

From source file:edu.ucsd.crbs.cws.App.java

License:asdf

public static void getJobAsJson(OptionSet optionSet) throws Exception {
    JobRestDAOImpl jobDAO = new JobRestDAOImpl();
    jobDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
    User u = getUserFromOptionSet(optionSet);
    jobDAO.setUser(u);/*from  w ww.j a  v a2 s  .  c  om*/

    Job j = jobDAO.getJobById(((Long) optionSet.valueOf(GET_JOB_ARG)).toString());
    if (j != null) {
        ObjectMapper om = new ObjectMapper();
        ObjectWriter ow = om.writerWithDefaultPrettyPrinter();
        System.out.println(ow.writeValueAsString(j));
    } else {
        System.err.println(
                "Unable to retreive job with id: " + ((Long) optionSet.valueOf(GET_JOB_ARG)).toString());
        System.exit(1);
    }
    return;

}

From source file:com.auditbucket.engine.service.EngineConfig.java

private void doHealth() {
    ObjectMapper om = new ObjectMapper();
    try {/*from   w  w w .jav a  2 s. c o m*/
        ObjectWriter or = om.writerWithDefaultPrettyPrinter();
        logger.info("\r\n" + or.writeValueAsString(getHealth()));

    } catch (JsonProcessingException e) {

        logger.error("doHealth", e);
    }
}

From source file:org.loklak.objects.AbstractIndexEntry.java

public String toString() {
    try {/*from  w w  w. j  a v a2  s.  com*/
        ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
        return ow.writeValueAsString(this.toMap());
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return "";
    }
}

From source file:com.blockwithme.lessobjects.util.JSONParser.java

/**
 * To json string./*from  w  w w . j  a  v a2 s  .c  om*/
 *
 * @return the string
 */
@SuppressWarnings("null")
public String toJSONString() {

    if (jsonString == null) {
        if (fromSchema) {
            try {
                final ObjectWriter writer = initMapper();
                jsonString = writer.writeValueAsString(schema);
            } catch (final JsonProcessingException jpe) {
                throw new IllegalStateException(jpe.getMessage(), jpe);
            }
        } else {
            try {
                if (format == SchemaFormat.JSON) {
                    jsonString = jsonOrXMLString;
                } else {
                    if (xmlString == null) {
                        xmlString = jsonOrXMLString;
                    }
                    final XmlMapper xmlMapper = new XmlMapper();
                    schema = xmlMapper.readValue(jsonOrXMLString, StructSchema.class);
                    final ObjectMapper jsonMapper = new ObjectMapper();
                    jsonString = jsonMapper.writeValueAsString(schema);
                }
            } catch (final IOException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
    }
    return jsonString;
}

From source file:cn.org.once.cstack.volumes.VolumeControllerTestIT.java

private String getString(VolumeResource volumeResource, ObjectMapper mapper) throws JsonProcessingException {
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    return ow.writeValueAsString(volumeResource);
}

From source file:org.osiam.resources.helper.AttributesRemovalHelper.java

private <T extends Resource> SCIMSearchResult<T> getJsonResponseWithAdditionalFields(
        SCIMSearchResult<T> scimSearchResult, Map<String, Object> parameterMap) {

    ObjectMapper mapper = new ObjectMapper();

    String[] fieldsToReturn = (String[]) parameterMap.get("attributes");
    ObjectWriter writer = getObjectWriter(mapper, fieldsToReturn);

    try {/*from ww w .j a v a  2s . co m*/
        String resourcesString = writer.writeValueAsString(scimSearchResult.getResources());
        JsonNode resourcesNode = mapper.readTree(resourcesString);

        String schemasString = writer.writeValueAsString(scimSearchResult.getSchemas());
        JsonNode schemasNode = mapper.readTree(schemasString);

        ObjectNode rootNode = mapper.createObjectNode();
        rootNode.put("totalResults", scimSearchResult.getTotalResults());
        rootNode.put("itemsPerPage", scimSearchResult.getItemsPerPage());
        rootNode.put("startIndex", scimSearchResult.getStartIndex());
        rootNode.put("schemas", schemasNode);
        rootNode.put("Resources", resourcesNode);

        return mapper.readValue(rootNode.toString(), SCIMSearchResult.class);
    } catch (IOException e) {
        LOGGER.warn("Unable to serialize search result", e);
        throw new OsiamBackendFailureException();
    }
}