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

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

Introduction

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

Prototype

public ObjectWriter writer() 

Source Link

Document

Convenience method for constructing ObjectWriter with default settings.

Usage

From source file:net.koddistortion.swagger.SwaggerApiClient.java

public static void main(String[] args) throws IOException {
    SwaggerApiClient c = new SwaggerApiClient();
    c.setBaseUrl("http://petstore.swagger.wordnik.com/api/api-docs");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ResourceListing listing = c.getResourceListing();
    ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
    for (Resource resource : listing.getApis()) {
        ApiDeclaration declaration = c.getApiDeclaration(resource);
        System.out.println(writer.writeValueAsString(declaration));
    }//ww w  .j  a  v a  2s .  c om
}

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

public static void main(String[] args) throws Exception {
    try {//from   w  w  w  .  j a  v a 2  s. co 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:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }/*  w w w  .j  a va  2s  .c om*/
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:be.dnsbelgium.rdap.client.RDAPCLI.java

public static void main(String[] args) {

    LOGGER.debug("Create the command line parser");
    CommandLineParser parser = new GnuParser();

    LOGGER.debug("Create the options");
    Options options = new RDAPOptions(Locale.ENGLISH);

    try {/* w  w w .j a  va 2 s  .c o m*/
        LOGGER.debug("Parse the command line arguments");
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            printHelp(options);
            return;
        }

        if (line.getArgs().length == 0) {
            throw new IllegalArgumentException("You must provide a query");
        }
        String query = line.getArgs()[0];

        Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase())
                : guessQueryType(query);

        LOGGER.debug("Query: {}, Type: {}", query, type);

        try {
            SSLContextBuilder sslContextBuilder = SSLContexts.custom();
            if (line.hasOption(RDAPOptions.TRUSTSTORE)) {
                sslContextBuilder.loadTrustMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS)));
            }
            if (line.hasOption(RDAPOptions.KEYSTORE)) {
                sslContextBuilder.loadKeyMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)),
                                line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)),
                        line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray());
            }
            SSLContext sslContext = sslContextBuilder.build();

            final String url = line.getOptionValue(RDAPOptions.URL);
            final HttpHost host = Utils.httpHost(url);

            HashSet<Header> headers = new HashSet<Header>();
            headers.add(new BasicHeader("Accept-Language",
                    line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString())));
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext,
                            (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier()
                                    : new BrowserCompatHostnameVerifier())));

            if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                        new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME),
                                line.getOptionValue(RDAPOptions.PASSWORD)));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url);
            ObjectMapper mapper = new ObjectMapper();

            JsonNode json = null;
            switch (type) {
            case DOMAIN:
                json = rdapClient.getDomainAsJson(query);
                break;
            case ENTITY:
                json = rdapClient.getEntityAsJson(query);
                break;
            case AUTNUM:
                json = rdapClient.getAutNum(query);
                break;
            case IP:
                json = rdapClient.getIp(query);
                break;
            case NAMESERVER:
                json = rdapClient.getNameserver(query);
                break;
            }
            PrintWriter out = new PrintWriter(System.out, true);
            if (line.hasOption(RDAPOptions.RAW)) {
                mapper.writer().writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.PRETTY)) {
                mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.YAML)) {
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setPrettyFlow(true);
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                dumperOptions.setSplitLines(true);
                Yaml yaml = new Yaml(dumperOptions);
                Map data = mapper.convertValue(json, Map.class);
                yaml.dump(data, out);
            } else {
                mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json);
            }
            out.flush();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        printHelp(options);
        System.exit(-1);
    }
}

From source file:com.rusticisoftware.tincan.json.Mapper.java

public static ObjectWriter getWriter(Boolean pretty) {
    ObjectMapper mapper = getInstance();

    ObjectWriter writer;//w  ww.j  a v a2s .  co m
    if (pretty) {
        writer = mapper.writer().withDefaultPrettyPrinter();
    } else {
        writer = mapper.writer();
    }

    return writer;
}

From source file:edu.usd.btl.toolTree.OntoToTree.java

public static String getOntoJson() throws Exception {
    ObjectMapper treeMapper = new ObjectMapper(); //create new Jackson Mapper
    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 = treeMapper.writer().withDefaultPrettyPrinter();
    String edamJSON = treeMapper.writeValueAsString(nodeList);
    System.out.println("**** EDAM ONTOLOGY JSON ****" + edamJSON);

    return edamJSON;
}

From source file:io.coala.json.JsonUtil.java

/**
 * @param object the object to serialize/marshal as (pretty) JSON
 * @return the (pretty) JSON representation
 *//*  w  w  w  .  ja  va  2  s  . c o  m*/
public static String toJSON(final ObjectMapper om, final Object object) {
    try {
        return om
                // .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                .writer().withDefaultPrettyPrinter().writeValueAsString(object);
    } catch (final JsonProcessingException e) {
        return Thrower.rethrowUnchecked(e);
    }
}

From source file:io.coala.json.JsonUtil.java

/**
 * @param object the object to serialize/marshal
 * @return the (minimal) JSON representation
 *//*from w  w  w  . ja  v a 2s .  co  m*/
public static String stringify(final Object object) {
    final ObjectMapper om = getJOM();
    try {
        checkRegistered(om, object.getClass());
        return om.writer().writeValueAsString(object);
    } catch (final JsonProcessingException e) {
        Thrower.rethrowUnchecked(e);
        return null;
    }
}

From source file:com.adobe.cq.wcm.core.components.Utils.java

/**
 * Provided a {@code model} object and an {@code expectedJsonResource} identifying a JSON file in the class path, this method will
 * test the JSON export of the model and compare it to the JSON object provided by the {@code expectedJsonResource}.
 *
 * @param model                the Sling Model
 * @param expectedJsonResource the class path resource providing the expected JSON object
 *///from   w w  w. j a  v  a2  s.c  om
public static void testJSONExport(Object model, String expectedJsonResource) {
    Writer writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    PageModuleProvider pageModuleProvider = new PageModuleProvider();
    mapper.registerModule(pageModuleProvider.getModule());
    DefaultMethodSkippingModuleProvider defaultMethodSkippingModuleProvider = new DefaultMethodSkippingModuleProvider();
    mapper.registerModule(defaultMethodSkippingModuleProvider.getModule());
    try {
        mapper.writer().writeValue(writer, model);
    } catch (IOException e) {
        fail(String.format("Unable to generate JSON export for model %s: %s", model.getClass().getName(),
                e.getMessage()));
    }
    JsonReader outputReader = Json.createReader(IOUtils.toInputStream(writer.toString()));
    InputStream is = Thread.currentThread().getContextClassLoader().getClass()
            .getResourceAsStream(expectedJsonResource);
    if (is != null) {
        JsonReader expectedReader = Json.createReader(is);
        assertEquals(expectedReader.read(), outputReader.read());
    } else {
        fail("Unable to find test file " + expectedJsonResource + ".");
    }
    IOUtils.closeQuietly(is);
}

From source file:org.apache.nifi.processors.ParseCSV.ParseCSV.java

public static String writeAsJson(List<Map<?, ?>> data) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    //mapper.writeValue(file, data);
    return mapper.writer().withDefaultPrettyPrinter().writeValueAsString(data);
}