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:org.usd.edu.btl.cli.ConvertBets.java

public void toIplant(String inputS, String output) {
    ObjectMapper betsMapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    BETSV1 betsTool; //create new seqTool
    ObjectWriter iplantWriter = betsMapper.writer().withDefaultPrettyPrinter();

    //map input json files to iplant class
    try {/*w w w .  j  av a 2 s. c  o  m*/
        betsTool = betsMapper.readValue(input, BETSV1.class);

        IplantV1 iplantOutput = BETSConverter.toIplant(betsTool);
        String iplantOutputJson = iplantWriter.writeValueAsString(iplantOutput); //write Json as String
        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            System.err.println("************************************************\n"
                    + "*********PRINTING OUT CONVERSION************\n"
                    + "--------------BETS --> Iplant--------------\n"
                    + "************************************************\n");
            //print objects as Json using jackson

            System.err.println("=== iPlant TO BETS JSON - OUTPUT === \n" + iplantOutputJson);
        } else {
            System.err.println("Writing to file...");
            //write to files
            iplantWriter.writeValue(new File(output), iplantOutput);
            System.err.println(output + " has been created successfully");
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.orange.ngsi2.model.EntityTest.java

@Test
public void serializationEntityTest() throws JsonProcessingException {
    ObjectWriter writer = Utils.objectMapper.writer(new DefaultPrettyPrinter());

    Entity entity = new Entity("Bcn-Welt", "Room");
    HashMap<String, Attribute> attributes = new HashMap<String, Attribute>();
    Attribute tempAttribute = new Attribute(21.7);
    attributes.put("temperature", tempAttribute);
    Attribute humidityAttribute = new Attribute(60);
    attributes.put("humidity", humidityAttribute);
    entity.setAttributes(attributes);//from  w  w  w. j  a va  2  s. c om
    String json = writer.writeValueAsString(entity);
    String jsonString = "{\n" + "  \"id\" : \"Bcn-Welt\",\n" + "  \"type\" : \"Room\",\n"
            + "  \"temperature\" : {\n" + "    \"value\" : 21.7,\n" + "    \"metadata\" : { }\n" + "  },\n"
            + "  \"humidity\" : {\n" + "    \"value\" : 60,\n" + "    \"metadata\" : { }\n" + "  }\n" + "}";
    assertEquals(jsonString, json);
}

From source file:com.google.api.tools.framework.importers.swagger.AuthBuilder.java

/**
 * Verified if the extension schema is correct.
 *//*  w  ww  . j ava  2  s  .  c  o  m*/
private List<Map<String, SecurityReq>> getSecurityRequirements(Object securityReqExt) {
    Gson gson = new GsonBuilder().create();
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    Type typeSecurityReqExtension = new TypeToken<List<Map<String, SecurityReq>>>() {
    }.getType();
    try {
        String jsonString = ow.writeValueAsString(securityReqExt);
        return gson.fromJson(jsonString, typeSecurityReqExtension);
    } catch (JsonProcessingException | JsonParseException ex) {
        return null;
    }
}

From source file:com.groupon.odo.controllers.PathController.java

@RequestMapping(value = "/api/path/test", method = RequestMethod.GET)
public @ResponseBody String testPath(@RequestParam String url, @RequestParam String profileIdentifier,
        @RequestParam Integer requestType) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);

    List<EndpointOverride> trySelectedRequestPaths = PathOverrideService.getInstance().getSelectedPaths(
            Constants.OVERRIDE_TYPE_REQUEST, ClientService.getInstance().findClient("-1", profileId),
            ProfileService.getInstance().findProfile(profileId), url, requestType, true);

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(trySelectedRequestPaths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter(
            "Filter properties from the PathController GET",
            SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}

From source file:com.groupon.odo.controllers.PathController.java

@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/path", method = RequestMethod.GET)
public @ResponseBody String getPathsForProfile(Model model, String profileIdentifier,
        @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter,
        @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID)
        throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID,
            typeFilter);/*  w  ww .j av a2s. com*/

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter(
            "Filter properties from the PathController GET",
            SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}

From source file:org.opencb.cellbase.lib.impl.GeneMongoDBAdaptor.java

@Override
public QueryResult<Gene> get(Query query, QueryOptions options) {
    Bson bson = parseQuery(query);//from  w  w  w  . ja  v  a2s.c o  m
    options = addPrivateExcludeOptions(options);

    if (postDBFilteringParametersEnabled(query)) {
        QueryResult<Document> nativeQueryResult = postDBFiltering(query, mongoDBCollection.find(bson, options));
        QueryResult<Gene> queryResult = new QueryResult<Gene>(nativeQueryResult.getId(),
                nativeQueryResult.getDbTime(), nativeQueryResult.getNumResults(),
                nativeQueryResult.getNumTotalResults(), nativeQueryResult.getWarningMsg(),
                nativeQueryResult.getErrorMsg(), null);
        ObjectMapper jsonObjectMapper = new ObjectMapper();
        jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
        ObjectWriter objectWriter = jsonObjectMapper.writer();
        queryResult.setResult(nativeQueryResult.getResult().stream().map(document -> {
            try {
                return this.objectMapper.readValue(objectWriter.writeValueAsString(document), Gene.class);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }).collect(Collectors.toList()));
        return queryResult;
    } else {
        return mongoDBCollection.find(bson, null, Gene.class, options);
    }
}

From source file:com.groupon.odo.controllers.PathController.java

@RequestMapping(value = "/api/path", method = RequestMethod.POST)
public @ResponseBody String addPath(Model model, String profileIdentifier,
        @RequestParam(value = "pathName") String pathName, @RequestParam(value = "path") String path,
        @RequestParam(value = "bodyFilter", required = false) String bodyFilter,
        @RequestParam(value = "contentType", required = false) String contentType,
        @RequestParam(value = "requestType", required = false) Integer requestType,
        @RequestParam(value = "groups[]", required = false) Integer[] groups,
        @RequestParam(value = "global", defaultValue = "false") Boolean global, HttpServletResponse response)
        throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);

    // TODO: Update UI to display the appropriate error message for this
    if (pathName.equals("test")) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "Cannot add path.  \"test\" is a reserved path name.";
    }//from w w  w  .jav a2s  . c om

    if (pathName.contains("/")) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "Cannot add path.  Path names cannot contain \"/\"";
    }

    // test regex parsing of the path
    try {
        Pattern pattern = Pattern.compile(path);
    } catch (PatternSyntaxException pse) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "Cannot add path.  Path regular expression is not valid.";
    }

    int pathId = pathOverrideService.addPathnameToProfile(profileId, pathName, path);
    if (groups != null) {
        //then adds all the groups
        for (int j = 0; j < groups.length; j++)
            pathOverrideService.AddGroupByNumber(profileId, pathId, groups[j]);
    }

    pathOverrideService.setContentType(pathId, contentType);
    pathOverrideService.setRequestType(pathId, requestType);
    pathOverrideService.setGlobal(pathId, global);

    if (bodyFilter != null) {
        pathOverrideService.setBodyFilter(pathId, bodyFilter);
    }

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter writer = objectMapper.writer();

    return writer.writeValueAsString(pathOverrideService.getPath(pathId));
}

From source file:org.usd.edu.btl.cli.ConvertBld.java

public void toBets(String inputS, String output) {
    ObjectMapper bldMapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    BLDV1 bldTool; //create new seqTool
    ObjectWriter oW = bldMapper.writer().withDefaultPrettyPrinter();
    try {//  ww  w .jav a 2  s .  co  m
        //map input json files to iplant class
        bldTool = bldMapper.readValue(input, BLDV1.class);
        //            String seqInputJson = oW.writeValueAsString(bldTool); //write Json as String
        //            System.out.println("=====BLD INPUT FILE =====");
        //            System.out.println(seqInputJson);

        BETSV1 betsOutput = BLDConverter.toBETS(bldTool);
        String betsOutputJson = oW.writeValueAsString(betsOutput); //write Json as String
        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            System.err.println("************************************************\n"
                    + "*********PRINTING OUT FIRST CONVERSION************\n"
                    + "--------------Seq --> BETS--------------\n"
                    + "************************************************\n");
            //print objects as Json using jackson

            System.err.println("=== BLD TO BETS JSON - OUTPUT === \n");
            System.out.println(betsOutputJson);
        } else {
            System.err.println("Writing to file...");
            //write to files
            oW.writeValue(new File(output), betsOutput);
            System.err.println(output + " has been created successfully");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

From source file:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/templates/{templateid}", method = RequestMethod.GET)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> getTemplateById(
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @PathVariable("templateid") long templateIdStr,
        // @RequestParam(value = "outformat", required=false) String
        // outformat,
        // @RequestParam(value = "o", required=false) String o
        @RequestParam Map<String, String> allParams) {

    try {// w ww . j a v a  2  s .  com
        // validateTemplateID(templateIdStr);
        // NOTE: outformat was defaulted to JSON before! Now it is TURTLE.
        NIFParameterSet nifParameters = this.normalizeNif(null, acceptHeader, null, allParams, true);
        HttpHeaders responseHeaders = new HttpHeaders();
        // check read access
        Template template = templateDAO.findOneById(templateIdStr);

        String serialization;
        if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            serialization = ow.writeValueAsString(template);
        } else {
            serialization = rdfConversionService.serializeRDF(template.getRDF(), nifParameters.getOutformat());
        }
        responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType());
        return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);

    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.broker.exception.AccessDeniedException();
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (OwnedResourceNotFoundException ex) {
        logger.error(ex.getMessage(), ex);
        throw new TemplateNotFoundException("Template not found. " + ex.getMessage());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new InternalServerErrorException("Unknown problem. Please contact us.");
    }
}

From source file:com.acentera.utils.ProjectsHelpers.java

public static String updateServer(Long projectId, Long serverId, JSONObject updatedServer)
        throws JsonProcessingException {

    SecurityController.checkPermission(projectId, PermisionTagConstants.SERVER, serverId,
            PermissionActionConstats.EDIT);

    ProjectDevices device = DeviceImpl.getProjectDevice(projectId, serverId);

    //Device device = projectDevice.getDevice();

    Session s = HibernateSessionFactory.getSession();

    if (updatedServer.containsKey("tags")) {
        JSONArray listOfTags = updatedServer.getJSONArray("tags");

        final Set<ProjectDevicesTags> tags = device.getTags();
        Set<ProjectDevicesTags> newTags = new HashSet<ProjectDevicesTags>();

        for (ProjectDevicesTags tag : tags) {
            tag.disable();//  w  w w.  ja v a2s  .  com
        }

        int len = listOfTags.size();
        for (int i = 0; i < len; i++) {
            JSONObject jsoData = listOfTags.getJSONObject(i);
            String data = jsoData.getString("name");

            List<ProjectDevicesTags> foundItem = select(tags,
                    having(on(ProjectDevicesTags.class).getName(), equalTo(data)));

            ProjectDevicesTags projectTags = null;
            if (foundItem.size() == 1) {
                //We found it..
                projectTags = foundItem.get(0);
            } else {
                //This tag is not in this object yet.
                projectTags = new ProjectDevicesTags();
            }
            projectTags.setProjectTags(
                    ProjectTagsImpl.getOrCreateTags(device.getProject(), data, TagConstants.ANY));
            projectTags.enable();

            tags.add(projectTags);
            s.saveOrUpdate(projectTags);
            newTags.add(projectTags);
        }

        //Set the new Tags
        device.setTags(tags);

        s.saveOrUpdate(device);

        //Since we disabled all data now.. lets return the object.
        device.setTags(newTags);

        //Do not return the provider object as someone will potentially call "save on the object"

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        ObjectWriter ow = mapper.writer();
        JSONObject jsoRes = new JSONObject();
        jsoRes.put("servers", ow.writeValueAsString(device));
        //return device;//ProjectsHelpers.getProjectProvidersAsJson(provider);
        return jsoRes.toString();
    }

    return null;
}