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

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

Introduction

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

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:com.asimihsan.handytrowel.cli.Main.java

public void doMain(String[] args)
        throws SAXException, CmdLineException, TimeoutException, BoilerpipeProcessingException, IOException {
    CmdLineParser parser = new CmdLineParser(this);
    parser.setUsageWidth(80);//from www  .j  a v a  2s  .c om
    try {
        parser.parseArgument(args);
        if (arguments.isEmpty())
            throw new CmdLineException(parser, "No arguments were given");
    } catch (final CmdLineException e) {
        System.err.println(e.getMessage());
        System.err.println("handytrowel [URL]");
        parser.printUsage(System.err);
        System.err.println();
        throw e;
    }
    String url = arguments.get(0);

    HTMLFetcher htmlFetcher = new HTMLFetcherBuilder().timeoutMillis(30 * 10000).build();
    String pageSource = null;
    try {
        pageSource = htmlFetcher.getPageSource(url);
    } catch (final TimeoutException e) {
        e.printStackTrace();
        throw e;
    }

    String extractedBody = null;
    List<String> links = null;
    try {
        final HTMLDocument htmlDoc = new HTMLDocument(pageSource);
        final TextDocument doc = new BoilerpipeSAXInput(htmlDoc.toInputSource()).getTextDocument();
        ArticleExtractor.INSTANCE.process(doc);
        final InputSource is = htmlDoc.toInputSource();
        links = LinkExtractor.INSTANCE.process(doc, is);
        /*
         * working article sentences extractor
         * !!AI do I have to call this again, or can I piggy back on LinkExtractor?
         */
        extractedBody = ArticleExtractor.INSTANCE.getText(pageSource);

    } catch (BoilerpipeProcessingException e) {
        e.printStackTrace();
        throw e;
    }

    TextAnalyzer analyzer = new TextAnalyzerBuilder().body(extractedBody).build().analyze();
    List<String> tokens = analyzer.getTokens();

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    Map<String, Object> articleData = new HashMap<>();
    articleData.put("extractedBody", extractedBody);
    articleData.put("links", links);
    articleData.put("tokens", tokens);
    try {
        mapper.writeValue(System.out, articleData);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
        throw e;
    } catch (JsonMappingException e) {
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:net.roboconf.dm.rest.commons.json.JSonBindingUtilsTest.java

@Test
public void testInstanceBinding_2() throws Exception {

    final String result = "{\"name\":\"server\",\"path\":\"/server\",\"status\":\"STARTING\",\"channels\":[\"channel4\",\"hop\"]}";
    ObjectMapper mapper = JSonBindingUtils.createObjectMapper();

    Instance inst = new Instance("server").channel("channel4").channel("hop").status(InstanceStatus.STARTING);
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, inst);
    String s = writer.toString();

    Assert.assertEquals(result, s);//w w w .  j av a  2s  .co  m
    Instance readInst = mapper.readValue(result, Instance.class);
    Assert.assertEquals(inst, readInst);
    Assert.assertEquals(inst.getName(), readInst.getName());
    Assert.assertEquals(inst.getStatus(), readInst.getStatus());
    Assert.assertEquals(inst.channels, readInst.channels);
}

From source file:net.roboconf.dm.rest.commons.json.JSonBindingUtilsTest.java

@Test
public void testApplicationBinding_2() throws Exception {

    final String result = "{\"name\":\"my application\",\"qualifier\":\"v1-17.snapshot\",\"namespace\":\"net.roboconf\"}";
    ObjectMapper mapper = JSonBindingUtils.createObjectMapper();

    Application app = new Application("my application").qualifier("v1-17.snapshot").namespace("net.roboconf");
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, app);
    String s = writer.toString();

    Assert.assertEquals(result, s);//from  www.  j a v a2s . c om
    Application readApp = mapper.readValue(result, Application.class);
    Assert.assertEquals(app, readApp);
    Assert.assertEquals(app.getName(), readApp.getName());
    Assert.assertEquals(app.getDescription(), readApp.getDescription());
    Assert.assertEquals(app.getQualifier(), readApp.getQualifier());
    Assert.assertEquals(app.getNamespace(), readApp.getNamespace());
}

From source file:com.almende.eve.rpc.jsonrpc.JSONRequest.java

/**
 * Write object.//www.ja  v  a  2s  .  c om
 *
 * @param out the out
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writeObject(final java.io.ObjectOutputStream out) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    mapper.writeValue(out, req);
}

From source file:dk.lnj.swagger4ee.AbstractJSonTest.java

public void makeCompare(SWRoot root, String expFile) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // make deserializer use JAXB annotations (only)
    mapper.setAnnotationIntrospector(introspector);
    // make serializer use JAXB annotations (only)

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, root);
    mapper.writeValue(new FileWriter(new File("lasttest.json")), root);

    String actual = sw.toString();
    String expected = new String(Files.readAllBytes(Paths.get(expFile)));

    String[] exp_split = expected.split("\n");
    String[] act_split = actual.split("\n");

    for (int i = 0; i < exp_split.length; i++) {
        String exp = exp_split[i];
        String act = act_split[i];
        String shortFileName = expFile.substring(expFile.lastIndexOf("/"));
        Assert.assertEquals(shortFileName + ":" + (i + 1), superTrim(exp), superTrim(act));
    }/*w w  w .  j a v  a2  s.  co  m*/

}

From source file:org.fusesource.restygwt.examples.server.GreetingServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("Creating custom greeting.");
    try {/*from   www  .  j a  v a2 s.  co  m*/
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode nameObject = mapper.readValue(req.getInputStream(), ObjectNode.class);
        String name = nameObject.get("name").asText();

        String greeting = "Hello " + name;
        ObjectNode resultObject = new ObjectNode(JsonNodeFactory.instance);
        resultObject.put("greeting", greeting);
        mapper.writeValue(resp.getOutputStream(), resultObject);
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        System.out.flush();
        System.err.flush();
    }
}

From source file:de.ks.flatadocdb.index.GlobalIndex.java

public void flush() {
    Path folder = repository.getPath().resolve(INDEX_FOLDER);
    if (!Files.exists(folder)) {
        try {/*  w w  w .  jav  a 2 s.  c o  m*/
            Files.createDirectories(folder);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    final ObjectMapper mapper = getMapper();
    ArrayList<IndexElement> elements = new ArrayList<>(idToElement.values());
    try {
        mapper.writeValue(repository.getPath().resolve(INDEX_FOLDER).resolve(INDEX_FILE).toFile(), elements);

        List<QueryWrapper> wrappers = queryElements.entrySet().stream()
                .map(entry -> new QueryWrapper(entry.getKey().getOwnerClass(), entry.getKey().getName(),
                        entry.getValue()))
                .collect(Collectors.toList());
        mapper.writeValue(repository.getPath().resolve(INDEX_FOLDER).resolve(QUERY_FILE).toFile(), wrappers);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.pnc.mavenrepositorymanager.AbstractRepositoryManagerDriverTest.java

@Before
public void setup() throws Exception {
    fixture = newServerFixture();/*from   w w w . j a v  a  2 s  . c o m*/

    Properties sysprops = System.getProperties();
    oldIni = sysprops.getProperty(CONFIG_SYSPROP);

    url = fixture.getUrl();
    File configFile = temp.newFile("pnc-config.json");
    ModuleConfigJson moduleConfigJson = new ModuleConfigJson("pnc-config");
    MavenRepoDriverModuleConfig mavenRepoDriverModuleConfig = new MavenRepoDriverModuleConfig(fixture.getUrl());
    mavenRepoDriverModuleConfig.setInternalRepoPatterns(getInternalRepoPatterns());
    PNCModuleGroup pncGroup = new PNCModuleGroup();
    pncGroup.addConfig(mavenRepoDriverModuleConfig);
    moduleConfigJson.addConfig(pncGroup);

    ObjectMapper mapper = new ObjectMapper();
    PncConfigProvider<MavenRepoDriverModuleConfig> pncProvider = new PncConfigProvider<MavenRepoDriverModuleConfig>(
            MavenRepoDriverModuleConfig.class);
    pncProvider.registerProvider(mapper);
    mapper.writeValue(configFile, moduleConfigJson);

    sysprops.setProperty(CONFIG_SYSPROP, configFile.getAbsolutePath());
    System.setProperties(sysprops);

    fixture.start();

    if (!fixture.isStarted()) {
        final BootStatus status = fixture.getBootStatus();
        throw new IllegalStateException("server fixture failed to boot.", status.getError());
    }

    Properties props = new Properties();
    props.setProperty("base.url", url);

    System.out.println("Using base URL: " + url);

    Configuration config = new Configuration();
    driver = new RepositoryManagerDriver(config);
}

From source file:de.stadtrallye.rallyesoft.model.map.MapManager.java

private void saveMapConfig() {
    ObjectMapper mapper = Serialization.getJsonInstance();
    configLock.readLock().lock();/*  w  w w.  j  ava2  s .com*/
    try {
        mapper.writeValue(Storage.getMapConfigOutputStream(), mapConfig);
    } catch (IOException e) {
        Log.e(THIS, "Failed to save MapConfig", e);
    } finally {
        configLock.readLock().unlock();
    }
}

From source file:monasca.thresh.utils.StatsdMetricConsumer.java

private String mapToJsonStr(Map<String, String> inputMap) {
    String results = new String();
    ObjectMapper mapper = new ObjectMapper();
    StringWriter sw = new StringWriter();

    try {/*from  www  .  j  a  v a  2 s.com*/
        mapper.writeValue(sw, inputMap);
        results = sw.toString();
    } catch (JsonGenerationException e) {
        logger.error("{}", e);
    } catch (JsonMappingException e) {
        logger.error("{}", e);
    } catch (IOException e) {
        logger.error("{}", e);
    }

    return results;
}