public Object createObject(JSONObject jsonObject, String type) { try { if (LOG.isDebugEnabled()) LOG.debug(String.format("Creating message from %s", jsonObject)); if (StringUtils.isEmpty(type)) { throw new MessageCreationException( String.format("Failed to create message: no message type found in JSON")); } Class<?> messageClass = applicationTypeMap.get(type); LOG.debug("Message class: " + messageClass); if (messageClass == null) { throw new MessageCreationException(String.format("Unknown message type: %s", type)); } // Constructor<? extends KoalaMessage> constructor = // messageClass.getConstructor(JSONObject.class); Object res = koalaJsonParser.getObject(jsonObject.toString(), messageClass); if (res instanceof KoalaMessageBase) ((KoalaMessageBase) res).setKoalaJsonParser(koalaJsonParser); return res; } catch (IllegalArgumentException e) { throw new MessageCreationException( String.format(FAILED_TO_CREATE_MESSAGE_WITH_TYPE_S, type), e); } catch (SecurityException e) { throw new MessageCreationException( String.format(FAILED_TO_CREATE_MESSAGE_WITH_TYPE_S, type), e); } }
@Test public void shouldConvertOldPendingToCreating() { // setup KoalaJsonParser koalaJsonParser = new KoalaJsonParser(); String json = "{ \"status\" : \"PENDING\", \"type\" : \"Volume\", \"device\" : \"device\", \"instanceId\" : \"inst\", \"attachedStatus\" : null, \"attachTime\" : 0, \"sizeInGigaBytes\" : 0, \"url\" : \"vol:vol\", \"createTime\" : 0, \"availabilityZone\" : null, \"ownerId\" : \"owner\", \"volumeId\" : \"vol\", \"statusTimestamp\" : 1271436743946, \"snapshotId\" : null, \"version\" : 0}"; // act Volume reverse = (Volume) koalaJsonParser.getObject(json, Volume.class); // assert assertEquals(VolumeState.CREATING, reverse.getStatus()); }
@Test public void shouldJsonRoundTrip() { // setup KoalaJsonParser koalaJsonParser = new KoalaJsonParser(); Volume volume1 = new Volume("owner", "vol", "inst", "device", VolumeState.CREATING, 0l); // act String json = koalaJsonParser.getJson(volume1); Volume reverse = (Volume) koalaJsonParser.getObject(json, Volume.class); // assert assertEquals(volume1, reverse); }