Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#reader()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#reader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TapiDeviceHelper.java    From onos with Apache License 2.0 6 votes vote down vote up
protected static Set<String> getUuids(DeviceId deviceId, DriverHandler handler) {
    RestSBController controller = checkNotNull(handler.get(RestSBController.class));
    ObjectMapper om = new ObjectMapper();
    final ObjectReader reader = om.reader();
    InputStream response = controller.get(deviceId, CONN_REQ_GET_API, MediaType.APPLICATION_JSON_TYPE);
    JsonNode jsonNode;
    try {
        jsonNode = reader.readTree(response);
        if (jsonNode == null) {
            log.error("JsonNode is null for response {}", response);
            return ImmutableSet.of();
        }
        return parseTapiGetConnectivityRequest(jsonNode);
    } catch (IOException e) {
        log.error("Exception while reading response {}", response, e);
        return ImmutableSet.of();
    }
}
 
Example 2
Source File: JsonStreamingArrayParser.java    From emodb with Apache License 2.0 6 votes vote down vote up
private JsonStreamingArrayParser(InputStream in, ObjectMapper mapper, Type elementType) {
    try {
        JavaType javaType = mapper.constructType(elementType);
        //noinspection unchecked
        _type = (Class<? extends T>) javaType.getRawClass();
        _jp = mapper.getFactory().createJsonParser(in);
        _reader = mapper.reader(javaType);

        // Parse at least the first byte of the response to make sure the input stream is valid.
        if (_jp.nextToken() != JsonToken.START_ARRAY) {
            throw new JsonParseException("Invalid JSON response, expected content to start with '[': " +
                    _jp.getCurrentToken(), _jp.getTokenLocation());
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 3
Source File: LoadTask.java    From bitsy with Apache License 2.0 5 votes vote down vote up
public LoadTask(CommittableFileLog[] inputs, MemoryGraphStore store, int opsPerNonTxCommit, ObjectMapper mapper, boolean safeMode) { 
    this.inputs = inputs;
    this.store = store;
    this.totalVE = 0;
    this.opsPerNonTxCommit = opsPerNonTxCommit;
    this.mapper = mapper;
    this.vReader = mapper.reader(VertexBeanJson.class);
    this.eReader = mapper.reader(EdgeBeanJson.class);
    this.repairMode = safeMode;
}
 
Example 4
Source File: CienaRestDevice.java    From onos with Apache License 2.0 5 votes vote down vote up
private JsonNode get(String uri) throws IOException {
    InputStream response = controller.get(deviceId, uri, MediaType.valueOf(MediaType.APPLICATION_JSON));
    ObjectMapper om = new ObjectMapper();
    final ObjectReader reader = om.reader();
    // all waveserver responses contain data node, which contains the requested data
    return reader.readTree(response).get(DATA);
}
 
Example 5
Source File: JWTParser.java    From java-jwt with MIT License 5 votes vote down vote up
private void addDeserializers(ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    ObjectReader reader = mapper.reader();
    module.addDeserializer(Payload.class, new PayloadDeserializer(reader));
    module.addDeserializer(Header.class, new HeaderDeserializer(reader));
    mapper.registerModule(module);
}
 
Example 6
Source File: PostgresWalRecord.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public Field getField() {
  if (field == null) {
    if (decoder == null) {
      return field;
    }
    switch(decoder) {

      case WAL2JSON:
        JsonNode json;
        try {
          ObjectMapper om = new ObjectMapper();
          ObjectReader reader = om.reader();
          json = reader.readTree(bufferToString());

          field = JsonUtil.jsonToField(om.convertValue(json, Map.class));
        } catch (IOException e) {
          field = null;
        }
        break;

      default:
        field = null; //should be null but here explicitly to highlight
        break;
    }

  }

  return field;
}
 
Example 7
Source File: JsonHelper.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static List<RunningQuery> readRunningQueryList(InputStream is)
		throws JsonProcessingException, IOException {

	final ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	final TypeFactory typeFactory = mapper.getTypeFactory();
	final ObjectReader reader = mapper.reader(typeFactory
			.constructCollectionType(List.class,
					com.bigdata.rdf.sail.model.RunningQuery.class));

	// TODO: Change this when upgrading to a newer Jackson version
	return (List<RunningQuery>) reader.readValue(is);

}
 
Example 8
Source File: JsonTargetConfigurationSerializer.java    From buck with Apache License 2.0 5 votes vote down vote up
public JsonTargetConfigurationSerializer(
    Function<String, UnconfiguredBuildTarget> buildTargetProvider) {
  this.buildTargetProvider = buildTargetProvider;
  ObjectMapper objectMapper = ObjectMappers.createWithEmptyBeansPermitted();
  SimpleModule targetConfigurationModule = new SimpleModule();
  targetConfigurationModule.addSerializer(
      BuildTarget.class, new BuildTargetSimpleSerializer(BuildTarget.class));
  objectMapper.registerModule(targetConfigurationModule);

  objectReader = objectMapper.reader();
  objectWriter = objectMapper.writer();
}
 
Example 9
Source File: PredictionServiceResultTest.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Test
public void createFromJSONPreditionsAndMeta() throws JsonProcessingException, IOException
{
	String json = "{\"meta\":{\"modelName\":\"amodel\"},\"predictions\":[{\"predictedClass\":\"cl1\",\"prediction\":1.0,\"confidence\":0.9}]}";
	ObjectMapper mapper = new ObjectMapper();
	ObjectReader reader = mapper.reader(PredictionServiceResult.class);
	PredictionServiceResult res = reader.readValue(json);
	Assert.assertNotNull(res);
	Assert.assertEquals(1.0, res.predictions.get(0).prediction);
	Assert.assertEquals("amodel", res.getMeta().modelName);
}
 
Example 10
Source File: PredictionServiceResultTest.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Test
public void createFromJSONPredictionsOnly() throws JsonProcessingException, IOException
{
	String json = "{\"predictions\":[{\"predictedClass\":\"cl1\",\"prediction\":1.0,\"confidence\":0.9}]}";
	ObjectMapper mapper = new ObjectMapper();
	ObjectReader reader = mapper.reader(PredictionServiceResult.class);
	PredictionServiceResult res = reader.readValue(json);
	Assert.assertNotNull(res);
	Assert.assertEquals(1.0, res.predictions.get(0).prediction);
}
 
Example 11
Source File: ConnectionInformationSerializer.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new ConnectionInformationSerializer
 *
 * @param objectMapper The preconfigured objectMapper
 */
private ConnectionInformationSerializer(ObjectMapper objectMapper) {
	ValidationUtil.requireNonNull(objectMapper, "objectMapper");
	this.objectMapper = objectMapper;
	this.objectWriter = objectMapper.writer();
	ObjectReader reader = objectMapper.reader();
	this.connectionStatisticsReader = reader.forType(ConnectionStatistics.class);
	this.connectionConfigurationReader = reader.forType(ConnectionConfiguration.class);
}
 
Example 12
Source File: RecordTest.java    From bitsy with Apache License 2.0 5 votes vote down vote up
public void testDictionaryMaxProperties() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectReader reader = mapper.reader(VertexBeanJson.class);

    String json = "{\"id\":\"40026fee-498a-4cd9-afad-1ae31363c13e\",\"v\":1,\"s\":\"M\",\"p\":{\"a00\":\"00\",\"a01\":\"01\",\"a02\":\"02\",\"a03\":\"03\",\"a04\":\"04\",\"a05\":\"05\",\"a06\":\"06\",\"a07\":\"07\",\"a08\":\"08\",\"a09\":\"09\",\"a10\":\"10\",\"a11\":\"11\",\"a12\":\"12\",\"a13\":\"13\",\"a14\":\"14\",\"a15\":\"15\",\"a16\":\"16\",\"a17\":\"17\",\"a18\":\"18\",\"a19\":\"19\",\"a20\":\"20\",\"a21\":\"21\",\"a22\":\"22\",\"a23\":\"23\",\"a24\":\"24\",\"a25\":\"25\",\"a26\":\"26\",\"a27\":\"27\",\"a28\":\"28\",\"a29\":\"29\",\"a30\":\"30\",\"a31\":\"31\",\"a32\":\"32\",\"a33\":\"33\",\"a34\":\"34\",\"a35\":\"35\",\"a36\":\"36\",\"a37\":\"37\",\"a38\":\"38\",\"a39\":\"39\",\"a40\":\"40\",\"a41\":\"41\",\"a42\":\"42\",\"a43\":\"43\",\"a44\":\"44\",\"a45\":\"45\",\"a46\":\"46\",\"a47\":\"47\",\"a48\":\"48\",\"a49\":\"49\",\"a50\":\"50\"}}";

    VertexBeanJson vBean = reader.readValue(json);

    int count = vBean.getProperties().size();
    assertEquals(51, count);
}
 
Example 13
Source File: ProductCompositeIntegration.java    From blog-microservices with Apache License 2.0 4 votes vote down vote up
private ObjectReader getReviewsReader() {
    if (reviewsReader != null) return reviewsReader;

    ObjectMapper mapper = new ObjectMapper();
    return reviewsReader = mapper.reader(new TypeReference<List<Review>>() {});
}
 
Example 14
Source File: OfflineSubreddit.java    From Slide with GNU General Public License v3.0 4 votes vote down vote up
public static OfflineSubreddit getSubreddit(String subreddit, Long time, boolean offline,
        Context c) {
    if (cache == null) cache = new HashMap<>();
    String title;
    if (subreddit != null) {
        title = subreddit.toLowerCase(Locale.ENGLISH) + "," + time;
    } else {
        title = "";
        subreddit = "";
    }
    if (cache.containsKey(title)) {
        return cache.get(title);
    } else {
        subreddit = subreddit.toLowerCase(Locale.ENGLISH);

        OfflineSubreddit o = new OfflineSubreddit();
        o.subreddit = subreddit.toLowerCase(Locale.ENGLISH);

        if (time == 0) {
            o.base = true;
        }

        o.time = time;

        String[] split = Reddit.cachedData.getString(subreddit.toLowerCase(Locale.ENGLISH) + "," + time, "")
                .split(",");
        if (split.length > 0) {
            o.time = time;
            o.submissions = new ArrayList<>();
            ObjectMapper mapperBase = new ObjectMapper();
            ObjectReader reader = mapperBase.reader();

            for (String s : split) {
                if (!s.contains("_")) s = "t3_" + s;
                if (!s.isEmpty()) {
                    try {
                        Submission sub = getSubmissionFromStorage(s, c, offline, reader);
                        if (sub != null) {
                            o.submissions.add(sub);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        } else {
            o.submissions = new ArrayList<>();
        }
        cache.put(title, o);
        return o;

    }
}
 
Example 15
Source File: JacksonRequest.java    From jus with Apache License 2.0 4 votes vote down vote up
public JacksonRequest(String method, HttpUrl url, ObjectMapper objectMapper) {
    this(method, url, objectMapper.reader());
}
 
Example 16
Source File: JacksonRequest.java    From jus with Apache License 2.0 4 votes vote down vote up
public JacksonRequest(String method, String url, ObjectMapper objectMapper) {
    this(method, url, objectMapper.reader());
}
 
Example 17
Source File: TestMapMessage.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testMapMessageSerializationWithJson() throws IOException {
    MapMessage message = new MapMessage("namespace", "name");
    message.addField("boolean", true);
    message.addField("boolean_array", Arrays.asList(new Boolean[] { true, false }));
    message.addField("byte", (byte) 1);
    message.addField("byte_array", Arrays.asList(new Byte[] { 2, 3, 4 }));
    message.addField("short", (short) 5);
    message.addField("short_array", Arrays.asList(new Short[] { 6, 7, 8 }));
    message.addField("int", 9);
    message.addField("int_array", Arrays.asList(new Integer[] { 10, 11, 12 }));
    message.addField("long", 13l);
    message.addField("long_array", Arrays.asList(new Long[] { 14l, 15l, 16l }));
    message.addField("float", 17.1f);
    message.addField("float_array", Arrays.asList(new Float[] { 18.1f, 19.1f, 20.1f }));
    message.addField("double", 21.1d);
    message.addField("double_array", Arrays.asList(new Double[] { 22.1d, 23.1d, 24.1d }));
    message.addField("bigdecimal", new BigDecimal("25.1"));
    message.addField("bigdecimal_array", Arrays.asList(new BigDecimal[] { new BigDecimal("26.1"), new BigDecimal("27.1"), new BigDecimal("28.1") }));
    message.addField("char", 'a');
    message.addField("char_array", Arrays.asList(new Character[] { 'b', 'c', 'd' }));
    message.addField("string", "ef");
    message.addField("string_array", Arrays.asList(new String[] { "gh", "jk", "lm" }));
    message.addField("localdatetime", DateTimeUtility.nowLocalDateTime());
    message.addField("localdatetime_array", Arrays.asList(new LocalDateTime[] { DateTimeUtility.nowLocalDateTime(), DateTimeUtility.nowLocalDateTime(), DateTimeUtility.nowLocalDateTime() }));
    message.addField("localdate", DateTimeUtility.nowLocalDate());
    message.addField("localdate_array", Arrays.asList(new LocalDate[] { DateTimeUtility.nowLocalDate(), DateTimeUtility.nowLocalDate(), DateTimeUtility.nowLocalDate() }));
    message.addField("localtime", DateTimeUtility.nowLocalTime());
    message.addField("localtime_array", Arrays.asList(new LocalTime[] { DateTimeUtility.nowLocalTime(), DateTimeUtility.nowLocalTime(), DateTimeUtility.nowLocalTime() }));
    
    MsgMetaData metaData = message.getMetaData();
    metaData.setDictionaryURI(SailfishURI.unsafeParse("plugin.dictionary"));
    metaData.setFromService("fromService");
    metaData.setToService("toService");
    metaData.setRawMessage(new byte[] { 1, 2, 3, 4, 5 });
    metaData.setServiceInfo(new ServiceInfo("id", new ServiceName("env", "serviceName")));
    
    MapMessage subMessage = message.cloneMessage();
    message.addField("message", subMessage);
    message.addField("message_array", Arrays.asList(new MapMessage[] { subMessage, subMessage }));
    
    ObjectMapper objectMapper = new ObjectMapper().enableDefaultTyping(DefaultTyping.NON_FINAL)
            .registerModule(new JavaTimeModule());
    ObjectReader reader = objectMapper.reader(IMessage.class);
    ObjectWriter writer = objectMapper.writer();
    
    String json = writer.writeValueAsString(message);
    
    IMessage message2 = reader.readValue(json);
    
    Assert.assertEquals(message, message2);
}
 
Example 18
Source File: AsyncTrelloHttpClient2.java    From trello-java-wrapper with Apache License 2.0 4 votes vote down vote up
public AsyncTrelloHttpClient2(AsyncHttpClient asyncHttpClient, ObjectMapper mapper) {
    this(asyncHttpClient, mapper.reader(), mapper.writer());
}
 
Example 19
Source File: ProductCompositeIntegration.java    From blog-microservices with Apache License 2.0 3 votes vote down vote up
private ObjectReader getProductReader() {

        if (productReader != null) return productReader;

        ObjectMapper mapper = new ObjectMapper();
        return productReader = mapper.reader(Product.class);
    }
 
Example 20
Source File: JacksonInstanceSerializer.java    From snowizard-discovery with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Constructor
 *
 * @param mapper
 *            {@link ObjectMapper}
 * @param typeRef
 *            {@link TypeReference}
 */
public JacksonInstanceSerializer(final ObjectMapper mapper,
        final TypeReference<ServiceInstance<T>> typeRef) {
    this.reader = mapper.reader();
    this.writer = mapper.writer();
    this.typeRef = typeRef;
}