MessageDeserializerFactory { public Message deserialize(String json) throws IOException { String type; try { JSONObject jsonObject = new JSONObject(json); type = jsonObject.getString(Message.FIELD_TYPE); } catch (JSONException e) { throw new IOException(e); } CustomMessageDeserializer cqb = typeToCustomQueryBuilder.get(type); if (cqb == null) { throw new IOException("The query type " + type + " does not have a corresponding deserializer."); } CustomMessageValidator cqv = typeToCustomQueryValidator.get(type); Object context = deserializationContext.get(typeToClass.get(type)); Message data = cqb.deserialize(json, typeToClass.get(type), context); LOG.debug("{}", data); if (data == null || !(cqv != null && cqv.validate(data, context))) { return null; } data.setType(type); return data; } MessageDeserializerFactory(Class<? extends Message>... schemas); void setContext(Class<? extends Message> clazz, Object context); Message deserialize(String json);  }
@Test public void testMalformedQuery() { @SuppressWarnings("unchecked") MessageDeserializerFactory qdf = new MessageDeserializerFactory(SchemaQuery.class); String malformed = "{\"}"; boolean exception = false; try { qdf.deserialize(malformed); } catch (IOException e) { exception = true; } Assert.assertTrue("Resulting query should throw IOException.", exception); }
@Test public void testUnregisteredQueryType() { @SuppressWarnings("unchecked") MessageDeserializerFactory qdf = new MessageDeserializerFactory(SchemaQuery.class); String unsupportedQuery = "{\"id\":\"1\",\"type\":\"Invalid type\"}"; boolean exception = false; Message data = null; try { data = qdf.deserialize(unsupportedQuery); } catch (IOException e) { exception = true; } Assert.assertTrue("Resulting query should be null.", exception); }