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

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

Introduction

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

Prototype

protected ObjectMapper(ObjectMapper src) 

Source Link

Document

Copy-constructor, mostly used to support #copy .

Usage

From source file:io.rodeo.chute.ChuteMain.java

public static void main(String[] args)
        throws SQLException, JsonParseException, JsonMappingException, IOException {
    InputStream is = new FileInputStream(new File(CONFIG_FILENAME));
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    ChuteConfiguration config = mapper.readValue(is, ChuteConfiguration.class);
    Map<String, Importer> importManagers = new HashMap<String, Importer>(config.importerConfigurations.size());
    for (Entry<String, ImporterConfiguration> importerConfig : config.importerConfigurations.entrySet()) {
        importManagers.put(importerConfig.getKey(), importerConfig.getValue().createImporter());
    }//from  w ww. j  ava 2 s . c  om
    Map<String, Exporter> exportManagers = new HashMap<String, Exporter>(config.exporterConfigurations.size());
    for (Entry<String, ExporterConfiguration> exporterConfig : config.exporterConfigurations.entrySet()) {
        exportManagers.put(exporterConfig.getKey(), exporterConfig.getValue().createExporter());
    }
    for (Entry<String, ConnectionConfiguration> connectionConfig : config.connectionConfigurations.entrySet()) {
        importManagers.get(connectionConfig.getValue().in)
                .addProcessor(exportManagers.get(connectionConfig.getValue().out));
    }

    for (Entry<String, Exporter> exportManager : exportManagers.entrySet()) {
        exportManager.getValue().start();
    }

    for (Entry<String, Importer> importManager : importManagers.entrySet()) {
        importManager.getValue().start();
    }
}

From source file:com.chiralBehaviors.autoconfigure.debug.TemplateDebugger.java

public static void main(String[] argv) throws JsonParseException, JsonMappingException, IOException {
    if (argv.length == 0) {
        System.out.println("Usage: TemplateDebugger <scenario file>+");
        System.exit(1);// w ww. j  a  va  2s. com
    }
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    for (String fileName : argv) {
        FileInputStream yaml = new FileInputStream(fileName);
        TemplateDebugger debugger = mapper.readValue(yaml, TemplateDebugger.class);
        System.out.println("======================================");
        System.out.println(String.format("Rendered output of %s", yaml));
        System.out.println("======================================");
        System.out.println();
        System.out.println(debugger.render());
        System.out.println();
        System.out.println("======================================");
        System.out.println();
        System.out.println();
    }
}

From source file:io.rhiot.spec.IoTSpec.java

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

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(Option.builder("c").longOpt(CONFIG).desc(
            "Location of the test configuration file. A default value is 'src/main/resources/test.yaml' for easy IDE testing")
            .hasArg().build());//from w  ww  .j av  a 2  s.co m

    options.addOption(Option.builder("i").longOpt(INSTANCE).desc("Instance of the test; A default value is 1")
            .hasArg().build());

    options.addOption(Option.builder("r").longOpt(REPORT)
            .desc("Location of the test report. A default value is 'target/report.csv'").hasArg().build());

    CommandLine line = parser.parse(options, args);
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    TestProfile test = mapper.readValue(new File(line.getOptionValue(CONFIG, "src/main/resources/test.yaml")),
            TestProfile.class);
    int instance = Integer.valueOf(line.getOptionValue(INSTANCE, "1"));
    test.setInstance(instance);
    String report = line.getOptionValue(REPORT, "target/report.csv");
    test.setReport(new CSVReport(report));

    LOG.info("Test '" + test.getName() + "' instance " + instance + " started");
    final List<Driver> drivers = test.getDrivers();
    ExecutorService executorService = Executors.newFixedThreadPool(drivers.size());
    List<Future<Void>> results = executorService.invokeAll(drivers, test.getDuration(), TimeUnit.MILLISECONDS);
    executorService.shutdownNow();
    executorService.awaitTermination(5, TimeUnit.SECONDS);

    results.forEach(result -> {
        try {
            result.get();
        } catch (ExecutionException execution) {
            LOG.warn("Exception running driver", execution);
        } catch (Exception interrupted) {
        }
    });

    drivers.forEach(driver -> {
        driver.stop();

        try {
            test.getReport().print(driver);
        } catch (Exception e) {
            LOG.warn("Failed to write reports for the driver " + driver);
        }
        LOG.debug("Driver " + driver);
        LOG.debug("\t " + driver.getResult());
    });
    test.getReport().close();

    LOG.info("Test '" + test.getName() + "' instance " + instance + " finished");

}

From source file:org.anhonesteffort.p25.ACAP25.java

public static void main(String[] args) {
    try {//from ww w  .  j  ava 2 s.com

        File systemsFile = new File("test.yml");
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        List<System> systems = Arrays.asList(mapper.readValue(systemsFile, System[].class));

        new ACAP25(systems).run();

    } catch (IOException | SamplesSourceException e) {
        e.printStackTrace();
    }
}

From source file:edu.sdsc.scigraph.owlapi.loader.BatchOwlLoader.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from  ww w  . j  a va2s .  co  m*/
    try {
        cmd = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BatchOwlLoader.class.getSimpleName(), getOptions());
        System.exit(-1);
    }

    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    OwlLoadConfiguration config = mapper.readValue(new File(cmd.getOptionValue('c').trim()),
            OwlLoadConfiguration.class);
    load(config);
    // TODO: Is Guice causing this to hang? #44
    System.exit(0);
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

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

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);//from   w w w  .  j  a  v a 2s. c  om
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:com.almende.eve.config.YamlReader.java

/**
 * Load./* w  ww .ja  va 2  s .c om*/
 * 
 * @param is
 *            the is
 * @return the config
 */
public static Config load(final InputStream is) {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    try {
        return Config.decorate((ObjectNode) mapper.readTree(is));
    } catch (final JsonProcessingException e) {
        LOG.log(Level.WARNING, "Couldn't parse Yaml file", e);
    } catch (final IOException e) {
        LOG.log(Level.WARNING, "Couldn't read Yaml file", e);
    }
    return null;
}

From source file:com.mirth.connect.util.MirthJsonUtil.java

public static String prettyPrint(String input) {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    try {/*  w  ww  . ja  v a2s.  c o  m*/
        // Modified Jackson's default pretty printer to separate each array element onto its own line
        DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
        prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
        JsonNode json = mapper.readTree(input);

        return mapper.writer(prettyPrinter).writeValueAsString(json);
    } catch (Exception e) {
        logger.warn("Error pretty printing json.", e);
    }

    return input;
}

From source file:com.huangyunkun.jviff.config.ConfigManager.java

public static Config getConfigFromFile(String filePath) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    Config config = mapper.readValue(new File(filePath), Config.class);
    if (StringUtils.isEmpty(config.getOutputDir())) {
        config.setOutputDir(Files.createTempDir().getAbsolutePath());
    }// ww  w. j a v  a  2s .  c  o  m
    return config;
}

From source file:fr.javatic.mongo.jacksonCodec.ObjectMapperFactory.java

public static ObjectMapper createObjectMapper() {
    BsonFactory bsonFactory = new BsonFactory();
    bsonFactory.enable(BsonParser.Feature.HONOR_DOCUMENT_LENGTH);

    return new ObjectMapper(bsonFactory);
}