List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValue
public void writeValue(Writer w, Object value) throws IOException, JsonGenerationException, JsonMappingException
From source file:org.apache.marmotta.client.clients.ConfigurationClient.java
/** * Update the configuration "key" with the given value. Value can be either a list of values or one of the * primitive types String, Boolean, Integer, Double * @param key//from w w w . ja v a 2 s . co m * @param value * @throws IOException * @throws MarmottaClientException */ public void setConfiguration(String key, final Object value) throws IOException, MarmottaClientException { HttpClient httpClient = HTTPUtil.createClient(config); String serviceUrl = config.getMarmottaUri() + URL_CONFIG_SERVICE + "/data/" + URLEncoder.encode(key, "utf-8"); HttpPost post = new HttpPost(serviceUrl); post.setHeader("Content-Type", "application/json"); ContentProducer cp = new ContentProducer() { @Override public void writeTo(OutputStream outstream) throws IOException { ObjectMapper mapper = new ObjectMapper(); if (value instanceof Collection) { mapper.writeValue(outstream, value); } else { mapper.writeValue(outstream, Collections.singletonList(value.toString())); } } }; post.setEntity(new EntityTemplate(cp)); try { HttpResponse response = httpClient.execute(post); switch (response.getStatusLine().getStatusCode()) { case 200: log.debug("configuration {} updated successfully", key); break; case 404: log.error("configuration with key {} does not exist", key); throw new NotFoundException("configuration with key " + key + " does not exist"); default: log.error("error updating configuration {}: {} {}", new Object[] { key, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() }); throw new MarmottaClientException( "error updating configuration " + key + ": " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } finally { post.releaseConnection(); } }
From source file:MappingTest.java
public void eventMappingTest() { String json = "{ \"_id\":{\"$oid\":\"53934cba30047a8c9f648508\"},\n" + " \"timestamp\":1402162485485,\n" + " \"endTime\":1402162487685,\n" + " \"appId\":\"demoApp\",\n" + " \"nodeId\":\"Node1\",\n" + " \"data\" : {\n" + " \"eventType\":\"VM_EXECUTION\",\n" + " \"message\":\"Job crashed with error 0x212\" }}"; ObjectMapper om = new ObjectMapper(); try {/* w w w. j ava 2 s . c om*/ Event e = om.readValue(json.getBytes(), Event.class); assertThat(e.getId()).isEqualToIgnoringCase("53934cba30047a8c9f648508"); assertThat(e.appId).isEqualToIgnoringCase("demoApp"); assertThat(e.data.get("eventType").asText()).isEqualTo("VM_EXECUTION"); om.writeValue(System.out, e); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:net.roboconf.dm.rest.commons.json.JSonBindingUtilsTest.java
@Test public void testComponentBinding_1() throws Exception { final String result = "{\"name\":\"component 1\",\"installer\":\"target\"}"; ObjectMapper mapper = JSonBindingUtils.createObjectMapper(); Component comp = new Component("component 1").installerName("target"); StringWriter writer = new StringWriter(); mapper.writeValue(writer, comp); String s = writer.toString(); Assert.assertEquals(result, s);/*w ww .j a va 2 s .c o m*/ Component readComp = mapper.readValue(result, Component.class); Assert.assertEquals(comp, readComp); Assert.assertEquals(comp.getName(), readComp.getName()); Assert.assertEquals(comp.getInstallerName(), readComp.getInstallerName()); }
From source file:net.hamnaberg.json.Collection.java
public void writeTo(Writer writer) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode obj = mapper.createObjectNode(); obj.set("collection", asJson()); mapper.writeValue(writer, obj); }
From source file:net.roboconf.dm.rest.commons.json.JSonBindingUtilsTest.java
@Test public void testApplicationBinding_1() throws Exception { final String result = "{\"name\":\"app1\",\"desc\":\"some text\",\"qualifier\":\"v1\"}"; ObjectMapper mapper = JSonBindingUtils.createObjectMapper(); Application app = new Application("app1").description("some text").qualifier("v1"); StringWriter writer = new StringWriter(); mapper.writeValue(writer, app); String s = writer.toString(); Assert.assertEquals(result, s);// w ww . j a va 2 s . co m 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()); }
From source file:io.fabric8.maven.plugin.HelmIndexMojo.java
@Override public void executeInternal() throws MojoExecutionException, MojoFailureException { outputFile.getParentFile().mkdirs(); log.info("Creating Helm Chart Index file at: %s", outputFile); List<ArtifactDTO> artifacts = searchMaven("?q=l:%22helm%22"); Map<String, ChartInfo> charts = new TreeMap<>(); for (ArtifactDTO artifact : artifacts) { addChartInfo(charts, artifact);// www.jav a 2 s .c om } Set<Map.Entry<String, ChartInfo>> entries = charts.entrySet(); for (Map.Entry<String, ChartInfo> entry : entries) { getLog().debug("" + entry.getKey() + " = " + entry.getValue()); } try { ObjectMapper mapper = KubernetesHelper.createYamlObjectMapper(); mapper.writeValue(outputFile, charts); } catch (IOException e) { throw new MojoExecutionException("Failed to write results as YAML to: " + outputFile + ". " + e, e); } generateHTML(outputHtmlFile, charts); }
From source file:org.jboss.pnc.indyrepositorymanager.AbstractRepositoryManagerDriverTest.java
@Before public void setup() throws Exception { fixture = newServerFixture();//from w ww. jav 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"); IndyRepoDriverModuleConfig mavenRepoDriverModuleConfig = new IndyRepoDriverModuleConfig(fixture.getUrl()); mavenRepoDriverModuleConfig.setInternalRepoPatterns(getInternalRepoPatterns()); SystemConfig systemConfig = new SystemConfig("", "", "JAAS", "4", "4", "4", "", "5", null, "14", "", "10"); PNCModuleGroup pncGroup = new PNCModuleGroup(); pncGroup.addConfig(mavenRepoDriverModuleConfig); pncGroup.addConfig(systemConfig); moduleConfigJson.addConfig(pncGroup); ObjectMapper mapper = new ObjectMapper(); PncConfigProvider<IndyRepoDriverModuleConfig> pncProvider = new PncConfigProvider<>( IndyRepoDriverModuleConfig.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:com.jyzn.wifi.validate.other.JacksonTest.java
@Test public void writeMapJSON() { ObjectMapper om = new ObjectMapper(); try {/*from w w w. j a va 2 s .c o m*/ JsonGenerator jg = om.getFactory().createGenerator(System.out, JsonEncoding.UTF8); ImmutableMap<String, String> map = ImmutableMap.of("status", "sucess", "validateCode", "123456"); jg.writeObject(map); //?om.writeValue/writeValueJsonGenerator.writeObject? om.writeValue(System.out, map); // om.writeValueAsString(map); } catch (IOException e) { } }
From source file:com.github.arnebinder.hide.swagger.params.HiderMojo.java
@SuppressWarnings("unchecked") public void execute() throws MojoExecutionException { getLog().info("Hide swagger elements with " + excludeKey + " \"" + excludeValue + "\"..."); getLog().info("Load swagger JSON descriptions file: " + jsonfile); ObjectMapper m = new ObjectMapper(); Map<String, Object> data; try {//ww w . ja v a 2 s .co m data = m.readValue(jsonfile, Map.class); invoke(data); if (overwriteJSON) { m.writeValue(jsonfile, data); } } catch (IOException e) { throw new MojoExecutionException("Could not read file: " + jsonfile, e); } ObjectMapper ym = new ObjectMapper(new YAMLFactory()); try { ym.writeValue(yamlfile, data); } catch (IOException e) { throw new MojoExecutionException("Could not write file: " + yamlfile, e); } if (mergeYamlFile != null) { getLog().info("Merge with yaml file: " + mergeYamlFile); JsonNode rootNode; JsonNode updateNode; try { rootNode = ym.readValue(yamlfile, JsonNode.class); updateNode = ym.readValue(mergeYamlFile, JsonNode.class); } catch (IOException e) { throw new MojoExecutionException("Could not read file: " + mergeYamlFile, e); } JsonNode merged = merge(rootNode, updateNode); try { ym.writeValue(yamlfile, merged); } catch (IOException e) { throw new MojoExecutionException("Could not write file: " + yamlfile, e); } getLog().info("Merging succeeded."); } getLog().info("Hiding succeeded."); }
From source file:org.fusesource.restygwt.examples.server.PizzaServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Processing Toppings Listing"); try {// w w w . j a va 2 s . c om ObjectMapper mapper = new ObjectMapper(); ArrayList<Topping> toppings = new ArrayList<Topping>(); toppings.add(new Topping("pineapple", 0.50)); toppings.add(new Topping("ham", 0.50)); toppings.add(new Topping("peperoni", 0.50)); StringWriter sw = new StringWriter(); mapper.writeValue(sw, toppings); System.out.println("Response: " + sw.toString()); resp.setContentType(Resource.CONTENT_TYPE_JSON); mapper.writeValue(resp.getOutputStream(), toppings); } catch (Throwable e) { e.printStackTrace(); } finally { System.out.flush(); System.err.flush(); } }