Esempio n. 1
0
  @Override
  @Transactional
  public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) {
    EntityDto entity = getEntity(entityRecord.getEntitySchemaId());
    validateCredentials(entity);
    validateNonEditableProperty(entity);

    List<FieldDto> entityFields = getEntityFields(entityRecord.getEntitySchemaId());

    try {
      MotechDataService service = getServiceForEntity(entity);
      Class<?> entityClass = getEntityClass(entity);

      boolean newObject = entityRecord.getId() == null;

      Object instance;
      if (newObject) {
        instance = entityClass.newInstance();

        for (FieldDto entityField : entityFields) {
          if (entityField.getType().isMap() && entityField.getBasic().getDefaultValue() != null) {
            setInstanceFieldMap(instance, entityField);
          }
        }

      } else {
        instance = service.retrieve(ID_FIELD_NAME, entityRecord.getId());
        if (instance == null) {
          throw new ObjectNotFoundException(entity.getName(), entityRecord.getId());
        }
      }

      updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, !newObject);

      if (newObject) {
        return service.create(instance);
      } else {
        return service.update(instance);
      }
    } catch (Exception e) {
      if (entityRecord.getId() == null) {
        throw new ObjectCreateException(entity.getName(), e);
      } else {
        throw new ObjectUpdateException(entity.getName(), entityRecord.getId(), e);
      }
    }
  }
Esempio n. 2
0
  @Test
  public void shouldReturnNewInstances() {
    mockSampleFields();
    mockEntity();

    EntityRecord record = instanceService.newInstance(ENTITY_ID);

    assertNotNull(record);
    assertEquals(Long.valueOf(ENTITY_ID), record.getEntitySchemaId());
    assertNull(record.getId());

    List<FieldRecord> fieldRecords = record.getFields();
    assertCommonFieldRecordFields(fieldRecords);
    assertEquals(
        asList("Default", 7, null, null, null),
        extract(fieldRecords, on(FieldRecord.class).getValue()));
  }
Esempio n. 3
0
  @Test
  public void shouldReturnEntityInstance() {
    mockDataService();
    mockSampleFields();
    mockEntity();
    when(motechDataService.retrieve("id", INSTANCE_ID))
        .thenReturn(new TestSample("Hello world", 99));

    EntityRecord record = instanceService.getEntityInstance(ENTITY_ID, INSTANCE_ID);

    assertNotNull(record);
    assertEquals(Long.valueOf(ENTITY_ID), record.getEntitySchemaId());
    assertEquals(Long.valueOf(INSTANCE_ID), record.getId());

    List<FieldRecord> fieldRecords = record.getFields();
    assertCommonFieldRecordFields(fieldRecords);
    assertEquals(
        asList("Hello world", 99, null, null, null),
        extract(fieldRecords, on(FieldRecord.class).getValue()));
  }