List of usage examples for com.fasterxml.jackson.databind ObjectMapper getFactory
@Override
public JsonFactory getFactory()
From source file:scott.barleyrs.rest.EntityResultMessageBodyWriter.java
@Override public void writeTo(Entity result, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { System.out.println("converting Entity to JSON"); result.getEntityContext().setEntityContextState(EntityContextState.INTERNAL); try {//from ww w .java2s . c o m ObjectMapper mapper = new ObjectMapper(); JsonGenerator gen = mapper.getFactory().createGenerator(entityStream); Set<Entity> started = new HashSet<>(); JsonNode json = toJson(mapper, result, started); gen.writeTree(json); } finally { result.getEntityContext().setEntityContextState(EntityContextState.USER); } }
From source file:org.n52.tamis.core.test.json.deserialize.SosTimeseriesInformationDeserializer_Test.java
/** * Parses the example document located at * "src/test/resources/SosTimeseriesInformation_example.json" and * deserializes its content into an instance of * {@link SosTimeseriesInformation}//from w w w .j a v a2 s .co m */ @Test public void test() { try { input = this.getClass().getResourceAsStream(SOS_TIMESERIES_INFORMATION_EXAMPLE_JSON); ObjectMapper objectMapper = new ObjectMapper(); JsonFactory jsonFactory = objectMapper.getFactory(); this.jsonParser = jsonFactory.createParser(input); SosTimeseriesInformation sosTimeseriesInformation = sosTimeseriesInformationDeserializer .deserialize(jsonParser, null); /* * Assert that values of the intantiated SosTimeseriesInformation * object match the expected parameters from the example document */ Assert.assertNotNull(sosTimeseriesInformation); /* * feature of interest */ Assert.assertEquals("sta_a4bff7499d440d9bb67ad73e048c5a47", sosTimeseriesInformation.getFeatureOfInterest()); /* * SOS URL */ Assert.assertEquals("http://pegelonline.wsv.de/webservices/gis/gdi-sos", sosTimeseriesInformation.getSosUrl()); /* * offering id */ Assert.assertEquals("off_c599e9b089385d08aa00b7c9c4c6f3ef", sosTimeseriesInformation.getOfferingId()); /* * procedure */ Assert.assertEquals("pro_e878d48e49ebc2a156e2810470bae9a2", sosTimeseriesInformation.getProcedure()); /* * observedProperty */ Assert.assertEquals("phe_f60bcfb1f6ac3d37210b5d757a1bf48e", sosTimeseriesInformation.getObservedProperty()); /* * temporal filter cannot be set via JsonDeserializer since the * document does not contain this information.! Thus, cannot be set! */ } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java
public String execute() throws Exception { final String assertion = buildAssertion(); final Map<String, String> requestParams = new HashMap<String, String>() { private static final long serialVersionUID = 1919397363313726934L; {/*from w ww. j a v a2 s . c om*/ put(REQUEST_PARAM_CLIENT_ID, clientId); put(REQUEST_PARAM_CLIENT_ASSERTION, java.net.URLEncoder.encode(assertion, "UTF-8")); } }; final String result = httpPost(requestParams); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(result); JsonNode obj = mapper.readTree(jp); JsonNode error = obj.findValue("Error"); if (error != null) throw new Exception(obj.findValue("Description").asText()); return obj.findValue("access_token").asText(); }
From source file:scott.barleyrs.rest.QueryResultMessageBodyWriter.java
@Override public void writeTo(QueryResult<?> result, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { System.out.println("converting QueryResult to JSON"); result.getEntityContext().setEntityContextState(EntityContextState.INTERNAL); try {/*from w w w . ja va2 s .c om*/ ObjectMapper mapper = new ObjectMapper(); JsonGenerator gen = mapper.getFactory().createGenerator(entityStream); ArrayNode array = mapper.createArrayNode(); for (Entity entity : result.getEntityList()) { Set<Entity> started = new HashSet<>(); array.add(toJson(mapper, entity, started)); } gen.writeTree(array); } finally { result.getEntityContext().setEntityContextState(EntityContextState.USER); } }
From source file:com.salmon.security.xacml.demo.springmvc.rest.controller.MarketPlacePopulatorController.java
@ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(HttpStatus.BAD_REQUEST)/*from w w w . ja v a 2 s .co m*/ public void whenPayloadIsStrange(HttpServletRequest request, HttpMessageNotReadableException ex) { StringBuilder sb = new StringBuilder("REQUEST PARTS: "); LOG.info("************************ JSON ERROR ************************ "); LOG.info("ContentType " + request.getContentType()); LOG.info("ContentLength " + request.getContentLength()); StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } LOG.info("************************ JSON PARSING ************************ "); LOG.info("Payload: " + jb.toString()); try { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(jb.toString()); JsonNode actualObj = mapper.readTree(jp); LOG.info("JSON OBJECT CREATED: " + actualObj.toString()); ObjectMapper driverMapper = new ObjectMapper(); Driver jsonDriver = driverMapper.readValue(actualObj.toString(), Driver.class); LOG.info("DRIVER OBJECT CREATED: " + jsonDriver.toString()); } catch (Exception e) { LOG.error("JSON Parsing Exception " + e.getMessage()); } }
From source file:org.apache.batchee.jackson.JacksonJSonWriter.java
@Override public void open(final Serializable checkpoint) throws Exception { final File outputFile = new File(file); if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { throw new BatchRuntimeException("Can't create " + outputFile.getAbsolutePath()); }/* w w w . jav a2 s. co m*/ final ObjectMapper mapper = Jacksons.newMapper(configuration); writer = new TransactionalWriter(outputFile, encoding, checkpoint); generator = mapper.getFactory().createGenerator(writer); if (fieldNameGeneratorClass != null) { if ("default".equals(fieldNameGeneratorClass)) { fieldNameGenerator = new DefaultFieldNameGenerator(); } else { fieldNameGenerator = FieldNameGenerator.class.cast(Thread.currentThread().getContextClassLoader() .loadClass(fieldNameGeneratorClass).newInstance()); } } if (useGlobalWrapper()) { if (fieldNameGenerator != null) { generator.writeStartObject(); } else { generator.writeStartArray(); } } }
From source file:org.duracloud.snapshot.rest.GeneralResourceTest.java
@Test public void testVersion() throws JsonParseException, IOException { replayAll();/* w w w . j av a 2 s . c o m*/ Response response = resource.version(); String message = (String) response.getEntity(); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createJsonParser(message); JsonNode obj = mapper.readTree(jp); Assert.assertNotNull(obj); Assert.assertNotNull(obj.get("version")); }
From source file:org.n52.tamis.core.test.json.deserialize.SingleProcessDescriptionDeserializer_Test.java
/** * Parses the example document located at * "src/test/resources/extendedSingleProcessDescription_example.json" and * deserializes its content into an instance of * {@link ProcessDescription_singleProcess} *//*from w w w .ja v a 2 s. co m*/ @Test public void test() { try { input = this.getClass().getResourceAsStream(EXTENDED_SINGLE_PROCESS_DESCRIPTION_EXAMPLE_JSON); ObjectMapper objectMapper = new ObjectMapper(); JsonFactory jsonFactory = objectMapper.getFactory(); this.jsonParser = jsonFactory.createParser(input); ProcessDescription_singleProcess singleProcessDescription_short = processesDeserializer .deserialize(jsonParser, null); /* * Assert that values of the intantiated * ProcessDescription_singleProcess object match the expected * parameters from the example document */ Assert.assertNotNull(singleProcessDescription_short); /* * id */ Assert.assertEquals("org.n52.tamis.algorithm.interpolation", singleProcessDescription_short.getId()); /* * label */ Assert.assertEquals("TAMIS Interpolation Process", singleProcessDescription_short.getLabel()); /* * inputs */ List<ProcessDescriptionInput> inputs = singleProcessDescription_short.getInputs(); Assert.assertEquals(3, inputs.size()); /* * first Input */ ProcessDescriptionInput firstInput = inputs.get(0); Assert.assertEquals("target-grid", firstInput.getId()); Assert.assertEquals("Target Grid", firstInput.getLabel()); Assert.assertEquals("text/xml | application/x-netcdf", firstInput.getType()); Assert.assertEquals(true, firstInput.getRequired()); /* * second Input */ ProcessDescriptionInput secondInput = inputs.get(1); Assert.assertEquals("interpolation-method", secondInput.getId()); Assert.assertEquals("Interpolation Method", secondInput.getLabel()); Assert.assertEquals("text/plain | text/xml", secondInput.getType()); Assert.assertEquals(true, secondInput.getRequired()); /* * third Input */ ProcessDescriptionInput thirdInput = inputs.get(2); Assert.assertEquals("input-values", thirdInput.getId()); Assert.assertEquals("Input Values", thirdInput.getLabel()); Assert.assertEquals("application/om+xml; version=2.0", thirdInput.getType()); Assert.assertEquals(true, thirdInput.getRequired()); /* * output(s) */ List<ProcessDescriptionOutput> outputs = singleProcessDescription_short.getOutputs(); Assert.assertEquals(1, outputs.size()); ProcessDescriptionOutput firstOutput = outputs.get(0); Assert.assertEquals("interpolated-values", firstOutput.getId()); Assert.assertEquals("Interpolated Values", firstOutput.getLabel()); Assert.assertEquals("application/geotiff | application/x-netcdf", firstOutput.getType()); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:io.seldon.external.ExternalPredictionServer.java
public JsonNode predict(String client, JsonNode jsonNode, OptionsHolder options) { long timeNow = System.currentTimeMillis(); URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME)); try {// w w w . ja v a 2s. c om URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort()) .setPath(uri.getPath()).setParameter("client", client) .setParameter("json", jsonNode.toString()); uri = builder.build(); } catch (URISyntaxException e) { throw new APIException(APIException.GENERIC_ERROR); } HttpContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(uri); try { if (logger.isDebugEnabled()) logger.debug("Requesting " + httpGet.getURI().toString()); CloseableHttpResponse resp = httpClient.execute(httpGet, context); try { if (resp.getStatusLine().getStatusCode() == 200) { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(resp.getEntity().getContent()); JsonNode actualObj = mapper.readTree(parser); return actualObj; } else { logger.error( "Couldn't retrieve prediction from external prediction server -- bad http return code: " + resp.getStatusLine().getStatusCode()); throw new APIException(APIException.GENERIC_ERROR); } } finally { if (resp != null) resp.close(); if (logger.isDebugEnabled()) logger.debug( "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms"); } } catch (IOException e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } catch (Exception e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } finally { } }
From source file:com.nebhale.cyclinglibrary.web.json.AbstractJsonSerializerTest.java
@Test public final void test() throws IOException, ParseException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new SimpleModule().addSerializer(new LinkJsonSerializer())); T value = getValue();/*w ww .jav a2s. c om*/ StringWriter out = new StringWriter(); JsonGenerator jsonGenerator = objectMapper.getFactory().createJsonGenerator(out); SerializerProvider serializerProvider = objectMapper.getSerializerProvider(); try { getJsonSerializer().serialize(value, jsonGenerator, serializerProvider); jsonGenerator.flush(); assertResult(out.toString()); } finally { out.close(); jsonGenerator.close(); } }