ItemHandlerFactoryImpl implements ItemHandlerFactory { @Override public ItemHandler get(Session session, MappedField field) { final Mapping mapping = field.getMapping(); if (mapping instanceof IdMapping) { return ID_HANDLER; } if (mapping.isPrimitiveOrWrappedType()) { return new PrimitiveHandler(); } if (mapping instanceof CollectionMapping) { final Class<?> fieldType = field.getType(); final Class<?> implementationType = mapping.getImplementationType(); final boolean primitive = mapping.isPrimitiveOrWrappedType() || String.class.equals(implementationType); if (List.class.equals(fieldType)) { if (primitive) { return new PrimitiveListHandler(session); } else { return new ReferenceListHandler(session); } } else if (Map.class.equals(fieldType)) { return new PrimitiveMapHandler(); } throw new IllegalArgumentException("Don't know how to create ItemHandler for " + field); } return new ReferenceHandler(session); }  @Override ItemHandler get(Session session, MappedField field);  }
@Test public void testCollectionHandler() { final MappedField field = new MappedFieldBuilder().withName("collection").withType(List.class).withCollectionMapping(List.class, String.class, "collection").create(); final ItemHandler itemHandler = factory.get(session, field); assertThat(itemHandler, notNullValue()); new ImmutablePersistenceRequest("primitive", String.class, Mode.Relative); final CollectionMapping collectionMapping = (CollectionMapping) field.getMapping(); final Collection<?> result = new ArrayList<String>(); final CollectionResult value = new ImmutableCollectionPersistenceResult(result); when(adapter.getCollection(collectionMapping)).thenReturn(value); final Object retrieve = itemHandler.retrieve(field, adapter); assertThat(retrieve, notNullValue()); assertThat(retrieve, instanceOf(List.class)); }
@Test public void testIdHandler() { final MappedField field = new MappedFieldBuilder().withName("id").withType(String.class).withIdMapping().create(); final ItemHandler itemHandler = factory.get(session, field); assertThat(itemHandler, notNullValue()); when(adapter.getId()).thenReturn("/some/id"); final Object retrieve = itemHandler.retrieve(field, adapter); assertThat(retrieve, notNullValue()); assertEquals("/some/id", retrieve); }
@Test public void testPrimitiveHandler() { final MappedField field = new MappedFieldBuilder().withName("primitive").withType(String.class).withPropertyMapping("primitive", String.class).create(); final ItemHandler itemHandler = factory.get(session, field); assertThat(itemHandler, notNullValue()); final PersistenceRequest request = new ImmutablePersistenceRequest("primitive", String.class, Mode.Relative); final PersistenceResult value = new ImmutablePersistenceResult("result"); when(adapter.getProperty(request)).thenReturn(value); final Object retrieve = itemHandler.retrieve(field, adapter); assertThat(retrieve, notNullValue()); assertEquals("result", retrieve); }