private EntityDto getEntity(Long entityId) {
   EntityDto entityDto = entityService.getEntity(entityId);
   if (entityDto == null) {
     throw new EntityNotFoundException(entityId);
   }
   return entityDto;
 }
  @Test(expected = EntityInstancesNonEditableException.class)
  public void shouldThrowExceptionWhileDeletingInstanceInNonEditableEntity() {
    EntityDto nonEditableEntity = new EntityDto();
    nonEditableEntity.setNonEditable(true);

    when(entityService.getEntity(ANOTHER_ENTITY_ID)).thenReturn(nonEditableEntity);

    instanceService.deleteInstance(ANOTHER_ENTITY_ID, INSTANCE_ID);
  }
  @Test(expected = EntityInstancesNonEditableException.class)
  public void shouldThrowExceptionWhileSavingInstanceInNonEditableEntity() {
    EntityDto nonEditableEntity = new EntityDto();
    nonEditableEntity.setNonEditable(true);
    nonEditableEntity.setId(ANOTHER_ENTITY_ID);
    EntityRecord entityRecord =
        new EntityRecord(null, ANOTHER_ENTITY_ID, new ArrayList<FieldRecord>());

    when(entityService.getEntity(ANOTHER_ENTITY_ID)).thenReturn(nonEditableEntity);

    instanceService.saveInstance(entityRecord);
  }
  @Test(expected = SecurityException.class)
  public void shouldThrowExceptionWhileReadingInstanceWithoutAnyPermission() {
    EntityDto entityDto = new EntityDto();
    entityDto.setReadOnlySecurityMode(SecurityMode.NO_ACCESS);
    entityDto.setSecurityMode(SecurityMode.NO_ACCESS);

    EntityRecord entityRecord =
        new EntityRecord(ANOTHER_ENTITY_ID, null, new ArrayList<FieldRecord>());

    when(entityService.getEntity(ANOTHER_ENTITY_ID)).thenReturn(entityDto);

    instanceService.getEntityRecords(entityRecord.getId());
  }
  private void mockAnotherEntity() {
    EntityDto entityWithRelatedField = mock(EntityDto.class);
    when(entityService.getEntity(ANOTHER_ENTITY_ID)).thenReturn(entityWithRelatedField);
    when(entityWithRelatedField.getClassName()).thenReturn(AnotherSample.class.getName());
    when(entityWithRelatedField.getName()).thenReturn(AnotherSample.class.getSimpleName());

    ServiceReference serviceReferenceForAnotherSample = mock(ServiceReference.class);
    when(bundleContext.getServiceReference(
            ClassName.getInterfaceName(AnotherSample.class.getName())))
        .thenReturn(serviceReferenceForAnotherSample);
    when(bundleContext.getService(serviceReferenceForAnotherSample))
        .thenReturn(serviceForAnotherSample);
  }
  @Test
  public void shouldLoadBlobField() throws InstanceNotFoundException {
    EntityDto entityDto = new EntityDto();
    entityDto.setReadOnlySecurityMode(null);
    entityDto.setSecurityMode(null);
    entityDto.setClassName(TestSample.class.getName());

    when(entityService.getEntity(ENTITY_ID + 1)).thenReturn(entityDto);
    mockDataService();
    TestSample instance = Mockito.mock(TestSample.class);
    when(motechDataService.findById(ENTITY_ID + 1)).thenReturn(instance);

    instanceService.getInstanceField(12l, ENTITY_ID + 1, "blobField");
    verify(motechDataService).getDetachedField(instance, "blobField");
  }
  @Test
  public void shouldAcceptUserWithNoPermissionWhileReadingInstanceWithNoSecurityMode() {
    EntityDto entityDto = new EntityDto();
    entityDto.setReadOnlySecurityMode(null);
    entityDto.setSecurityMode(null);
    entityDto.setClassName(TestSample.class.getName());

    EntityRecord entityRecord = new EntityRecord(ANOTHER_ENTITY_ID, null, new ArrayList<>());

    when(entityService.getEntity(ANOTHER_ENTITY_ID)).thenReturn(entityDto);

    mockDataService();
    instanceService.getEntityRecords(entityRecord.getId());

    verify(entityService).getEntityFieldsForUI(ANOTHER_ENTITY_ID);
  }
  @Override
  public List<FieldInstanceDto> getInstanceFields(Long entityId, Long instanceId) {
    EntityDto entity = entityService.getEntity(entityId);
    validateCredentialsForReading(entity);

    List<FieldDto> fields = entityService.getEntityFields(entityId);

    List<FieldInstanceDto> result = new ArrayList<>();
    for (FieldDto field : fields) {
      FieldInstanceDto fieldInstanceDto =
          new FieldInstanceDto(field.getId(), instanceId, field.getBasic());
      result.add(fieldInstanceDto);
    }

    return result;
  }
  @Test
  public void shouldNotUpdateGridSizeWhenUsernameIsBlank() {
    EntityDto entityDto = new EntityDto();
    entityDto.setReadOnlySecurityMode(null);
    entityDto.setSecurityMode(null);
    entityDto.setClassName(TestSample.class.getName());

    EntityRecord entityRecord = new EntityRecord(ENTITY_ID + 1, null, new ArrayList<FieldRecord>());

    when(entityService.getEntity(ENTITY_ID + 1)).thenReturn(entityDto);

    mockDataService();
    instanceService.getEntityRecords(entityRecord.getId(), new QueryParams(1, 100));

    verify(entityService).getEntityFieldsForUI(ENTITY_ID + 1);
    verify(userPreferencesService, never()).updateGridSize(anyLong(), anyString(), anyInt());
  }
  @Test
  public void shouldUpdateGridSize() {
    setUpSecurityContext();

    EntityDto entityDto = new EntityDto();
    entityDto.setReadOnlySecurityMode(null);
    entityDto.setSecurityMode(null);
    entityDto.setClassName(TestSample.class.getName());

    EntityRecord entityRecord = new EntityRecord(ENTITY_ID + 1, null, new ArrayList<>());

    when(entityService.getEntity(ENTITY_ID + 1)).thenReturn(entityDto);

    mockDataService();
    instanceService.getEntityRecords(entityRecord.getId(), new QueryParams(1, 100));

    verify(entityService).getEntityFieldsForUI(ENTITY_ID + 1);
    verify(userPreferencesService).updateGridSize(ENTITY_ID + 1, "motech", 100);
  }
 private void mockEntity(Class<?> entityClass, long entityId, EntityDto entity) {
   when(entityService.getEntity(entityId)).thenReturn(entity);
   when(entityService.getEntityByClassName(entityClass.getName())).thenReturn(entity);
   when(entity.getClassName()).thenReturn(entityClass.getName());
   when(entity.getId()).thenReturn(entityId);
 }
  @Test
  public void shouldUpdateRelatedFields() {
    TestSample test1 = new TestSample("someString", 4);
    TestSample test2 = new TestSample("otherString", 5);
    TestSample test3 = new TestSample("sample", 6);

    RelationshipsUpdate oneToOneUpdate = new RelationshipsUpdate();
    oneToOneUpdate.getAddedIds().add(6L);
    RelationshipsUpdate oneToManyUpdate = buildRelationshipUpdate();

    List<FieldRecord> fieldRecords =
        asList(
            FieldTestHelper.fieldRecord("title", String.class.getName(), "String field", "Default"),
            FieldTestHelper.fieldRecord(
                TypeDto.ONE_TO_MANY_RELATIONSHIP, "testSamples", "Related field", oneToManyUpdate),
            FieldTestHelper.fieldRecord(
                TypeDto.ONE_TO_ONE_RELATIONSHIP,
                "testSample",
                "Other Related field",
                oneToOneUpdate));

    EntityRecord entityRecord = new EntityRecord(null, ANOTHER_ENTITY_ID, fieldRecords);

    mockSampleFields();
    mockDataService();
    mockEntity();

    EntityDto entityWithRelatedField = mock(EntityDto.class);
    when(entityService.getEntity(ANOTHER_ENTITY_ID)).thenReturn(entityWithRelatedField);
    when(entityWithRelatedField.getClassName()).thenReturn(AnotherSample.class.getName());
    when(entityWithRelatedField.getId()).thenReturn(ENTITY_ID + 1);

    ServiceReference serviceReferenceForClassWithRelatedField = mock(ServiceReference.class);
    MotechDataService serviceForClassWithRelatedField = mock(MotechDataService.class);
    when(bundleContext.getServiceReference(
            ClassName.getInterfaceName(AnotherSample.class.getName())))
        .thenReturn(serviceReferenceForClassWithRelatedField);
    when(bundleContext.getService(serviceReferenceForClassWithRelatedField))
        .thenReturn(serviceForClassWithRelatedField);
    when(motechDataService.findById(4L)).thenReturn(test1);
    when(motechDataService.findById(5L)).thenReturn(test2);
    when(motechDataService.findById(6L)).thenReturn(test3);
    when(motechDataService.findByIds(oneToManyUpdate.getAddedIds()))
        .thenReturn(Arrays.asList(test1, test2));

    when(entityService.getEntityFieldsForUI(ANOTHER_ENTITY_ID))
        .thenReturn(
            asList(
                FieldTestHelper.fieldDto(
                    5L, "title", String.class.getName(), "String field", "Default"),
                FieldTestHelper.fieldDto(
                    6L,
                    "testSamples",
                    TypeDto.ONE_TO_MANY_RELATIONSHIP.getTypeClass(),
                    "Related field",
                    null)));

    ArgumentCaptor<AnotherSample> captor = ArgumentCaptor.forClass(AnotherSample.class);
    instanceService.saveInstance(entityRecord, null);

    verify(serviceForClassWithRelatedField).create(captor.capture());
    AnotherSample capturedValue = captor.getValue();
    assertEquals(capturedValue.getTestSample(), test3);
    assertEquals(capturedValue.getTestSamples().size(), 3);
    assertEquals(capturedValue.getTitle(), "Default");
    assertTrue(capturedValue.getTestSamples().contains(test1));
    assertFalse(capturedValue.getTestSamples().contains(test3));
    assertTrue(capturedValue.getTestSamples().contains(test2));
  }