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:test.jackson.JacksonNsgiRegister.java

public static void main(String[] args) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    RegisterContextRequest rcr = objectMapper.readValue(ngsiRcr, RegisterContextRequest.class);

    System.out.println(objectMapper.writeValueAsString(rcr));

    LinkedHashMap association = (LinkedHashMap) rcr.getContextRegistration().get(0).getContextMetadata().get(0)
            .getValue();/*from   ww  w.ja v a 2s  .c om*/
    Association assocObject = objectMapper.convertValue(association, Association.class);
    System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(1).getContextMetadata().get(0);

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:com.tmo.swagger.main.GenrateSwaggerJson.java

public static void main(String[] args)
        throws JsonGenerationException, JsonMappingException, IOException, EmptyXlsRows {

    PropertyReader pr = new PropertyReader();

    Properties prop = pr.readPropertiesFile(args[0]);
    //Properties prop =pr.readClassPathPropertyFile("common.properties");
    String swaggerFile = prop.getProperty("swagger.json");
    String sw = "";
    if (swaggerFile != null && swaggerFile.length() > 0) {
        Swagger swagger = populatePropertiesOnlyPaths(prop, new SwaggerParser().read(swaggerFile));
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        sw = mapper.writeValueAsString(swagger);
    } else {//from   w  w  w.  j  av a2s .c  o  m
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        Swagger swagger = populateProperties(prop);
        sw = mapper.writeValueAsString(swagger);
    }
    try {
        File file = new File(args[1] + prop.getProperty("path.operation.tags") + ".json");
        //File file = new File("src/main/resources/"+prop.getProperty("path.operation.tags")+".json");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(sw);
        logger.info("Swagger Genration Done!");
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.test.beans.JsonBeanTest.java

public static void main(String[] arg) throws IOException {
    System.out.println("Application Started");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    UserMaster um = mapper.readValue(userMasterJson, UserMaster.class);
    System.out.println(um);//www . ja  v a2 s .  c  o m
    UserTrans ut = mapper.readValue(userTransJson, UserTrans.class);
    System.out.println(ut);
    UserTrans utn = mapper.readValue(userTransJsonMore, UserTrans.class);
    System.out.println(utn);
    System.out.println(mapper.writeValueAsString(ut));

}

From source file:edu.usd.btl.ontology.ToolTree.java

public static void main(String[] args) throws Exception {
    try {/*w w  w .ja va  2s  .c  o  m*/
        //File ontoInput = new File(".\\ontology_files\\EDAM_1.3.owl");
        ObjectMapper mapper = new ObjectMapper();
        OntologyFileRead ontFileRead = new OntologyFileRead();
        ArrayList<edu.usd.btl.ontology.BioPortalElement> nodeList = ontFileRead
                .readFile(".\\ontology_files\\EDAM_1.3.owl");
        //write nodelist to JSON string
        ObjectWriter treeWriter = mapper.writer().withDefaultPrettyPrinter();
        String edamJSON = mapper.writeValueAsString(nodeList);

        JsonNode rootNode = mapper.readValue(edamJSON, JsonNode.class);
        System.out.println("IsNull" + rootNode.toString());

        OntSearch ontSearch = new OntSearch();
        System.out.println(nodeList.get(0).getURI());
        String result = ontSearch.searchElementByURI("http://edamontology.org/topic_2817");
        System.out.println("RESULT = " + result);

        String topicSearchResult = ontSearch.findAllTopics();
        System.out.println("Topics Result = " + topicSearchResult);

        File ontFile = new File(".\\ontology_files\\EDAM_1.3.owl");
        String searchFromFileResult = ontSearch.searchNodeFromFile("http://edamontology.org/topic_2817",
                ".\\ontology_files\\EDAM_1.3.owl");
        System.out.println("File Response = " + searchFromFileResult.toString());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

    //Hashmap stuff
    //        OntologyFileRead ontFileRead = new OntologyFileRead();
    //        ArrayList<edu.usd.btl.ontology.BioPortalElement> nodeList = ontFileRead.readFile(".\\ontology_files\\EDAM_1.3.owl");
    //        
    //        HashMap hm = new HashMap();
    //        
    //        //find topics
    //        ArrayList<OntologyNode> ontoTopicList = new ArrayList();
    //        
    //        for(BioPortalElement node : nodeList){
    //            //System.out.println("****" + node.getURI());
    //            hm.put(node.getURI(), node.getName());
    //        }
    //        
    //        Set set = hm.entrySet();
    //        Iterator i = set.iterator();
    //        while(i.hasNext()){
    //            Map.Entry me = (Map.Entry)i.next();
    //            System.out.println(me.getKey() + ": " + me.getValue());
    //        }
    //        System.out.println("HashMap Size = " + hm.size());
}

From source file:com.amazonaws.services.iot.client.sample.shadowEcho.ShadowEchoSample.java

public static void main(String args[])
        throws IOException, AWSIotException, AWSIotTimeoutException, InterruptedException {
    CommandArguments arguments = CommandArguments.parse(args);
    initClient(arguments);/*from w  w w .j a  v  a2s . c o  m*/

    String thingName = arguments.getNotNull("thingName", SampleUtil.getConfig("thingName"));
    AWSIotDevice device = new AWSIotDevice(thingName);

    awsIotClient.attach(device);
    awsIotClient.connect();

    // Delete existing document if any
    device.delete();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Thing thing = new Thing();

    while (true) {
        long desired = thing.state.desired.counter;
        thing.state.reported.counter = desired;
        thing.state.desired.counter = desired + 1;

        String jsonState = objectMapper.writeValueAsString(thing);

        try {
            // Send updated document to the shadow
            device.update(jsonState);
            System.out.println(System.currentTimeMillis() + ": >>> " + jsonState);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": update failed for " + jsonState);
            continue;
        }

        try {
            // Retrieve updated document from the shadow
            String shadowState = device.get();
            System.out.println(System.currentTimeMillis() + ": <<< " + shadowState);

            thing = objectMapper.readValue(shadowState, Thing.class);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": get failed for " + jsonState);
            continue;
        }

        Thread.sleep(1000);
    }

}

From source file:org.hcmut.emr.SessionBuilder.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    try (BufferedReader br = new BufferedReader(
            new FileReader("/home/sinhlk/myspace/emr/src/main/resources/patern"))) {
        ObjectMapper jsonMapper = new ObjectMapper();
        String line = br.readLine();
        Map<String, String> result = new HashMap<String, String>();
        List<NameValuePair> list = new ArrayList<>();

        while (line != null) {
            if (line != null && line != "") {
                list.add(new BasicNameValuePair(line.trim().toLowerCase(), SessionBuilder.buildValue(line)));
                result.put(line.trim().toLowerCase(), SessionBuilder.buildValue(line));
                line = br.readLine();//from  w  w  w . ja  v  a2  s  .c  om
            }
        }
        System.out.println(jsonMapper.writeValueAsString(list));
        File file = new File("/home/sinhlk/myspace/emr/src/main/resources/session.js");
        jsonMapper.writeValue(file, list);
    }

}

From source file:MondrianService.java

public static void main(String[] arg) {
    System.out.println("Starting Mondrian Connector for Infoveave");
    Properties prop = new Properties();
    InputStream input = null;/*from www .  j a va  2  s .  co m*/
    int listenPort = 9998;
    int threads = 100;
    try {
        System.out.println("Staring from :" + getSettingsPath());
        input = new FileInputStream(getSettingsPath() + File.separator + "MondrianService.properties");
        prop.load(input);
        listenPort = Integer.parseInt(prop.getProperty("port"));
        threads = Integer.parseInt(prop.getProperty("maxThreads"));
        if (input != null) {
            input.close();
        }
        System.out.println("Found MondrianService.Properties");
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }

    port(listenPort);
    threadPool(threads);
    enableCORS("*", "*", "*");

    ObjectMapper mapper = new ObjectMapper();
    MondrianConnector connector = new MondrianConnector();
    get("/ping", (request, response) -> {
        response.type("application/json");
        return "\"Here\"";
    });

    post("/cubes", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetCubes(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/measures", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetMeasures(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/dimensions", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.GetDimensions(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/cleanCache", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            return mapper.writeValueAsString(connector.CleanCubeCache(queryObject));
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });

    post("/executeQuery", (request, response) -> {
        response.type("application/json");
        try {
            Query queryObject = mapper.readValue(request.body(), Query.class);
            response.status(200);
            String content = mapper.writeValueAsString(connector.ExecuteQuery2(queryObject));
            return content;
        } catch (JsonParseException ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        } catch (Exception ex) {
            response.status(400);
            return mapper.writeValueAsString(new Error(ex.getMessage()));
        }
    });
}

From source file:org.jetbrains.webdemo.executors.JunitExecutor.java

public static void main(String[] args) {
    try {/*  w  ww.j  a va 2  s  .c o m*/
        JUnitCore jUnitCore = new JUnitCore();
        jUnitCore.addListener(new MyRunListener());
        List<Class> classes = getAllClassesFromTheDir(new File(args[0]));
        for (Class cl : classes) {
            boolean hasTestMethods = false;
            for (Method method : cl.getMethods()) {
                if (method.isAnnotationPresent(Test.class)) {
                    hasTestMethods = true;
                    break;
                }
            }
            if (!hasTestMethods)
                continue;

            Request request = Request.aClass(cl);
            jUnitCore.run(request);
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            SimpleModule module = new SimpleModule();
            module.addSerializer(Throwable.class, new ThrowableSerializer());
            module.addSerializer(junit.framework.ComparisonFailure.class,
                    new JunitFrameworkComparisonFailureSerializer());
            module.addSerializer(org.junit.ComparisonFailure.class, new OrgJunitComparisonFailureSerializer());
            objectMapper.registerModule(module);
            System.setOut(standardOutput);

            Map<String, List<TestRunInfo>> groupedTestResults = new HashMap<>();
            for (TestRunInfo testRunInfo : output) {
                if (!groupedTestResults.containsKey(testRunInfo.className)) {
                    groupedTestResults.put(testRunInfo.className, new ArrayList<TestRunInfo>());
                }
                groupedTestResults.get(testRunInfo.className).add(testRunInfo);
            }

            System.out.print(objectMapper.writeValueAsString(groupedTestResults));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Throwable e) {
        System.setOut(standardOutput);
        System.out.print("[\"");
        e.printStackTrace();
        System.out.print("\"]");
    }
}

From source file:com.ottogroup.bi.asap.operator.twitter.consumer.TwitterStreamConsumer.java

public static void main(String[] args) throws Exception {
    ObjectMapper m = new ObjectMapper();
    m.enable(SerializationFeature.INDENT_OUTPUT);

    ComponentConfiguration cfg = new ComponentConfiguration("twitter-stream-reader", ComponentType.SOURCE,
            "twitterStreamConsumer", "0.0.1");
    cfg.setComponentExceptionHandler(/*ww  w  .j  a  va 2 s .c  om*/
            new ExceptionHandlerConfiguration(ExceptionHandlerType.COMPONENT_EXCEPTION_HANDLER,
                    "twitterComponentExceptionHandler", "log4jExceptionHandler", "0.0.1"));
    cfg.setExecutorExceptionHandler(
            new ExceptionHandlerConfiguration(ExceptionHandlerType.EXECUTOR_EXCEPTION_HANDLER,
                    "twitterExecutorExceptionHandler", "log4jExceptionHandler", "0.0.1"));
    cfg.setMessageWaitStrategy(new MessageWaitStrategyConfiguration("twitterExecutorWaitStrategy",
            "sleepingMessageWaitStrategy", "0.0.1"));
    cfg.setMailbox(
            new MailboxConfiguration("twitterConsumerMailbox", "oneToOneConcurrentArrayQueueMailbox", "0.0.1"));
    cfg.addSubscription("simpleFilteringOperator");

    cfg.addSetting(TwitterStreamConsumer.CFG_TWITTER_CONSUMER_KEY, "<consumer_id>");
    cfg.addSetting(TwitterStreamConsumer.CFG_TWITTER_CONSUMER_SECRET, "<consumer_secret>");
    cfg.addSetting(TwitterStreamConsumer.CFG_TWITTER_PROFILES, "1,2,3");
    cfg.addSetting(TwitterStreamConsumer.CFG_TWITTER_TOKEN_KEY, "<token_key>");
    cfg.addSetting(TwitterStreamConsumer.CFG_TWITTER_TOKEN_SECRET, "<token_secret>");
    cfg.addSetting(TwitterStreamConsumer.CFG_TWITTER_TWEET_LANGUAGES, "DE,FR,EN");
    cfg.addSetting(TwitterStreamConsumer.CFG_TWITTER_TWEET_SEARCH_TERMS, "SOCCER,FOOTBALL,FUSSBALL");

    System.out.println(m.writeValueAsString(cfg));
}

From source file:com.metamx.datatypes.ExampleMain.java

public static void main(String[] args) throws Exception {
    final ObjectMapper objectMapper = new ObjectMapper();
    final MmxAuctionSummary auctionSummary = MmxAuctionSummary.builder()
            .timestamp(new DateTime("2014-01-01T00:00:00.000Z")).auctionType(2)
            .bcat(Arrays.asList("IAB26", "IAB25")).requestId("AFEWSEBD5EB5FI32DASFCD452BB78DVE")
            .ext(Ext.builder().put("custFlag", 3).put("custStr", "Unicorns are the best!").build())
            .app(App.builder().bundle("bundlename").cat(Arrays.asList("IAB1")).domain("unicornssay.com")
                    .id("12312312").name("Unicornssay")
                    .publisher(Publisher.builder().id("DSA1394D42D3").name("Unicornssay").build()).build())
            .site(Site.builder().cat(Arrays.asList("IAB1", "IAB2")).domain("unicornssay.com").id("1345135123")
                    .name("Unicornssay")
                    .publisher(Publisher.builder().id("pub12345").name("Publisher A").build()).build())
            .impressions(Arrays.asList(Imp.builder().tagId("231").bidFloor(0.1).secure(0)
                    .banner(Banner.builder().height(320).width(50).pos(3).api(Arrays.asList(3, 4)).build())
                    .displayManager("MyRenderer").displayManagerVer("v2").build()))
            .device(Device.builder().carrier("Verizon").connectionType(2).deviceType(1).didmd5("AA003")
                    .didsha1("AA023").dnt(0).dpidmd5("A400FABFB5").dpidsha1("AA0").flashVer("2.1").ifa("123")
                    .ip("192.168.1.8").jsSupport(1).language("en").macsha1("E50BB11").macmd5("BB11")
                    .make("Apple").model("iPhone 3GS").osVer("4.2.1").os("iOS").ua("Crazy UA String!")
                    .geo(Geo.builder().city("US-SFO").country("USA").lat(37.790148).lon(-122.434103)
                            .metro("807").region("CA").type(1).zip("94107").build())
                    .ext(Ext.builder().put("customField", "sam").build()).build())
            .user(User.builder().id("456789876567897654678987656789").yob(1987).gender("M")
                    .data(Arrays.asList(Data.builder().id("123").name("bluesky")
                            .segment(Arrays
                                    .asList(Segment.builder().id("abc1").name("gender").value("male").build()))
                            .build()))//ww  w .  j  a  v  a  2  s.  c  o  m
                    .build())
            .responses(Arrays.asList(MmxBidResponse.builder()
                    .timestamp(new DateTime("2014-03-05T04:58:23.200Z")).status(1).totalDuration(43L)
                    .bidderId("1921").bidderName("RealAds").cur("USD")
                    .seatBid(Arrays.asList(MmxSeatBid.builder().seat("512")
                            .bid(Arrays.asList(MmxBid.builder().id("1").impId("102").status(1).price(5.43)
                                    .clearPrice(1.1).adId("314").attr(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 12))
                                    .crId("1234").cId("229").adomain(Arrays.asList("realtime4real.mmx.org"))
                                    .iUrl("http://adserver.com/pathtosampleimage").build()))
                            .build()))
                    .build()))
            .build();
    System.out.println(objectMapper.writeValueAsString(auctionSummary));
}