KON-43 Units tests for ldap-service
diff --git a/src/main/java/org/eclipse/openk/contactbasedata/config/SchedulingConfig.java b/src/main/java/org/eclipse/openk/contactbasedata/config/SchedulerConfig.java
similarity index 95%
rename from src/main/java/org/eclipse/openk/contactbasedata/config/SchedulingConfig.java
rename to src/main/java/org/eclipse/openk/contactbasedata/config/SchedulerConfig.java
index 170f780..5440a66 100644
--- a/src/main/java/org/eclipse/openk/contactbasedata/config/SchedulingConfig.java
+++ b/src/main/java/org/eclipse/openk/contactbasedata/config/SchedulerConfig.java
@@ -11,7 +11,7 @@
 @Configuration
 @EnableScheduling
 @ConditionalOnProperty(prefix = "ldap.scheduling", name="enabled", havingValue="true", matchIfMissing = false)
-public class SchedulingConfig {
+public class SchedulerConfig {
 
     @Value("${ldap.scheduling.cron-expression}")
     private String cronExpression;
diff --git a/src/main/java/org/eclipse/openk/contactbasedata/service/InitPropertyLogger.java b/src/main/java/org/eclipse/openk/contactbasedata/service/InitPropertyLogger.java
index 92552b2..4399cfe 100644
--- a/src/main/java/org/eclipse/openk/contactbasedata/service/InitPropertyLogger.java
+++ b/src/main/java/org/eclipse/openk/contactbasedata/service/InitPropertyLogger.java
@@ -1,13 +1,10 @@
 package org.eclipse.openk.contactbasedata.service;
 
 import lombok.extern.log4j.Log4j2;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.boot.env.OriginTrackedMapPropertySource;
 import org.springframework.context.event.ContextRefreshedEvent;
 import org.springframework.context.event.EventListener;
 import org.springframework.core.env.AbstractEnvironment;
-import org.springframework.core.env.EnumerablePropertySource;
 import org.springframework.core.env.Environment;
 import org.springframework.core.env.MutablePropertySources;
 import org.springframework.stereotype.Component;
diff --git a/src/main/java/org/eclipse/openk/contactbasedata/service/LdapService.java b/src/main/java/org/eclipse/openk/contactbasedata/service/LdapService.java
index d52408d..791a5ac 100644
--- a/src/main/java/org/eclipse/openk/contactbasedata/service/LdapService.java
+++ b/src/main/java/org/eclipse/openk/contactbasedata/service/LdapService.java
@@ -15,18 +15,13 @@
 package org.eclipse.openk.contactbasedata.service;
 
 import org.eclipse.openk.contactbasedata.api.AuthNAuthApi;
-import org.eclipse.openk.contactbasedata.viewmodel.LdapUser;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
 import org.springframework.ldap.core.*;
 import org.springframework.ldap.support.LdapNameBuilder;
-import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.stereotype.Service;
 
 import javax.naming.Name;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Base64;
 import java.util.List;
 
 @Service
@@ -60,7 +55,7 @@
                         .get());
     }
 
-    public void create(final String username, final String password) {
+    public void create(final String username) {
         Name dn = LdapNameBuilder
                 .newInstance()
                 .add("ou", "users")
@@ -71,7 +66,6 @@
         context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
         context.setAttributeValue("cn", username);
         context.setAttributeValue("sn", username);
-        context.setAttributeValue("userPassword", digestSHA(password));
 
         ldapTemplate.bind(context);
     }
@@ -87,12 +81,12 @@
         context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" });
         context.setAttributeValue("cn", username);
         context.setAttributeValue("sn", username);
-        context.setAttributeValue("userPassword", digestSHA(password));
+        //context.setAttributeValue("userPassword", digestSHA(password));
 
         ldapTemplate.modifyAttributes(context);
     }
 
-    private String digestSHA(final String password) {
+    /*private String digestSHA(final String password) {
         String base64;
         try {
             MessageDigest digest = MessageDigest.getInstance("SHA");
@@ -104,7 +98,7 @@
             throw new RuntimeException(e);
         }
         return "{SHA}" + base64;
-    }
+    }*/
 
 
 }
diff --git a/src/main/java/org/eclipse/openk/contactbasedata/service/LdapUserService.java b/src/main/java/org/eclipse/openk/contactbasedata/service/LdapUserService.java
index d661238..4f2f1f6 100644
--- a/src/main/java/org/eclipse/openk/contactbasedata/service/LdapUserService.java
+++ b/src/main/java/org/eclipse/openk/contactbasedata/service/LdapUserService.java
@@ -13,6 +13,7 @@
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.ldap.core.LdapTemplate;
+import org.springframework.security.access.annotation.Secured;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
@@ -54,6 +55,7 @@
      * Retrieves all the LdapUsers in the ldap server, using {@link LdapUserAttributesMapper}
      * @return list of LdapUsers
      */
+    @Secured({"ROLE_KON-WRITER", "ROLE_KON-ADMIN"})
     public List<LdapUser> getAllLdapUsers() {
         return ldapTemplate.search(query()
                 .where("objectclass").is("person"), ldapUserAttributesMapper);
@@ -69,6 +71,7 @@
     }
 
     @Transactional
+    @Secured("ROLE_KON-ADMIN")
     public void synchronizeLDAP() {
         List<TblInternalPerson> internalPersonList = internalPersonRepository.findByUidNotNull();
 
@@ -76,26 +79,23 @@
                 Collectors.toMap(TblInternalPerson::getUid, Function.identity()));
 
         List<LdapUser> allFoundLdapUsers = new ArrayList<>();
-        List<TblInternalPerson> allNotExistingLdapUsers = new ArrayList<>();
-        findExistingAndNotExistingLdapUsers(internalPersonList, allFoundLdapUsers, allNotExistingLdapUsers);
-
         List<TblInternalPerson> internalPersonListSynchronized = new ArrayList<>();
+        findExistingAndNotExistingLdapUsers(internalPersonList, allFoundLdapUsers, internalPersonListSynchronized);
 
         RefCommunicationType refCommunicationTypeMail = getRefCommunicationType(mailId);
         RefCommunicationType refCommunicationTypePhone = getRefCommunicationType(telephoneNumberId);
 
         for (LdapUser ldapUser : allFoundLdapUsers) {
             TblInternalPerson tblInternalPerson = uidToInternalPersonMap.get(ldapUser.getUid());
-            if (tblInternalPerson == null) continue;
-            boolean attributesChanged = mapLdapUserToInternaPerson(tblInternalPerson, ldapUser, refCommunicationTypeMail, refCommunicationTypePhone);
-            if (attributesChanged) {
-                internalPersonListSynchronized.add(tblInternalPerson);
+            if (tblInternalPerson != null) {
+                boolean attributesChanged = mapLdapUserToInternalPerson(tblInternalPerson, ldapUser, refCommunicationTypeMail, refCommunicationTypePhone);
+                if (attributesChanged) {
+                    internalPersonListSynchronized.add(tblInternalPerson);
+                }
             }
         }
 
         //Update all not found users notes with the sync error message
-        internalPersonRepository.saveAll(allNotExistingLdapUsers);
-
         //Update all found Users with the synchronized LDAP data
         internalPersonRepository.saveAll(internalPersonListSynchronized);
     }
@@ -140,7 +140,7 @@
         }
     }
 
-    private boolean mapLdapUserToInternaPerson(TblInternalPerson tblInternalPerson, LdapUser ldapUser, RefCommunicationType refCommunicationTypeMail, RefCommunicationType refCommunicationTypePhone) {
+    private boolean mapLdapUserToInternalPerson(TblInternalPerson tblInternalPerson, LdapUser ldapUser, RefCommunicationType refCommunicationTypeMail, RefCommunicationType refCommunicationTypePhone) {
         boolean attributesChanged = false;
 
         attributesChanged = isCommunicationDataChangedAndSync(tblInternalPerson, ldapUser.getMail(), refCommunicationTypeMail, attributesChanged, mailId);
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 83830a7..9029383 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -34,7 +34,6 @@
     mail: mail
     department: department
     telephone-number: phone
-    password: userpassword
   db-id-mapping:
     mail-id: 1
     telephone-number-id: 2
diff --git a/src/test/java/org/eclipse/openk/contactbasedata/config/TestConfiguration.java b/src/test/java/org/eclipse/openk/contactbasedata/config/TestConfiguration.java
index 8d0468d..b12bcfb 100644
--- a/src/test/java/org/eclipse/openk/contactbasedata/config/TestConfiguration.java
+++ b/src/test/java/org/eclipse/openk/contactbasedata/config/TestConfiguration.java
@@ -17,6 +17,7 @@
 import org.eclipse.openk.contactbasedata.ContactBaseDataApplication;
 import org.eclipse.openk.contactbasedata.mapper.*;
 import org.eclipse.openk.contactbasedata.service.*;
+import org.eclipse.openk.contactbasedata.service.util.LdapUserAttributesMapper;
 import org.springframework.boot.autoconfigure.domain.EntityScan;
 import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
 import org.springframework.context.annotation.Bean;
@@ -72,6 +73,9 @@
     AssignmentModulContactMapper assignmentModulContactMapper() { return new AssignmentModulContactMapperImpl(); }
 
     @Bean
+    LdapUserAttributesMapper ldapUserAttributesMapper() { return new LdapUserAttributesMapper(); };
+
+    @Bean
     public VersionService myVersionService() {
         return new VersionService();
     }
@@ -117,4 +121,7 @@
 
     @Bean
     public ContactAnonymizerService myContactAnonymizerService() { return new ContactAnonymizerService(); }
+
+    @Bean
+    public LdapUserService myLdapUserService() { return new LdapUserService(); }
 }
diff --git a/src/test/java/org/eclipse/openk/contactbasedata/service/LdapUserServiceTest.java b/src/test/java/org/eclipse/openk/contactbasedata/service/LdapUserServiceTest.java
new file mode 100644
index 0000000..78290e3
--- /dev/null
+++ b/src/test/java/org/eclipse/openk/contactbasedata/service/LdapUserServiceTest.java
@@ -0,0 +1,174 @@
+/*
+ *******************************************************************************
+ * Copyright (c) 2019 Contributors to the Eclipse Foundation
+ *
+ * See the NOTICE file(s) distributed with this work for additional
+ * information regarding copyright ownership.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v. 2.0 which is available at
+ * http://www.eclipse.org/legal/epl-2.0.
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ *******************************************************************************
+ */
+package org.eclipse.openk.contactbasedata.service;
+
+import org.assertj.core.util.Lists;
+import org.eclipse.openk.contactbasedata.config.TestConfiguration;
+import org.eclipse.openk.contactbasedata.model.RefCommunicationType;
+import org.eclipse.openk.contactbasedata.model.TblInternalPerson;
+import org.eclipse.openk.contactbasedata.repository.CommunicationTypeRepository;
+import org.eclipse.openk.contactbasedata.repository.InternalPersonRepository;
+import org.eclipse.openk.contactbasedata.service.util.LdapUserAttributesMapper;
+import org.eclipse.openk.contactbasedata.support.MockDataHelper;
+import org.eclipse.openk.contactbasedata.viewmodel.LdapUser;
+import org.junit.jupiter.api.Test;
+import org.mockito.stubbing.Answer;
+import org.powermock.reflect.Whitebox;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.ldap.core.LdapTemplate;
+import org.springframework.ldap.query.LdapQuery;
+import org.springframework.test.context.ContextConfiguration;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+@DataJpaTest
+@ContextConfiguration(classes = {TestConfiguration.class})
+
+public class LdapUserServiceTest {
+    private static final long MAIL_ID = 1L;
+    private static final long TEL_ID = 2L;
+
+    @Qualifier("myLdapUserService")
+    @Autowired
+    private LdapUserService ldapUserService;
+
+    @Autowired
+    private LdapUserAttributesMapper ldapUserAttributesMapper;
+
+    @MockBean
+    private InternalPersonService internalPersonService;
+
+    @MockBean
+    private InternalPersonRepository internalPersonRepository;
+
+    @MockBean
+    private CommunicationTypeRepository communicationTypeRepository;
+
+    @MockBean
+    private LdapTemplate ldapTemplate;
+
+    @Test
+    public void shouldSynchronizeLDAPRunThrou1() {
+        List<TblInternalPerson> internalPeople = MockDataHelper.mockTblInternalPersonPage().getContent();
+        when( internalPersonRepository.findByUidNotNull() ).thenReturn(internalPeople);
+
+        List<LdapUser> ldapUserList = new ArrayList<>(1);
+        LdapUser ldapUser = MockDataHelper.mockLdapUser();
+        ldapUser.setUid(internalPeople.get(0).getUid());
+        ldapUserList.add( ldapUser );
+        // users are found
+        when( ldapTemplate.search(any(LdapQuery.class), any(LdapUserAttributesMapper.class))).thenReturn( ldapUserList );
+
+        List<RefCommunicationType> refCommunicationTypes = MockDataHelper.mockRefCommunicationTypeList();
+        Whitebox.setInternalState(ldapUserService, "mailId", MAIL_ID);
+        Whitebox.setInternalState(ldapUserService, "telephoneNumberId", TEL_ID);
+        refCommunicationTypes.get(1).setId(TEL_ID);
+        refCommunicationTypes.get(2).setId(MAIL_ID);
+        when( communicationTypeRepository.findAll()).thenReturn(refCommunicationTypes);
+
+        when(internalPersonRepository.saveAll(any( List.class)))
+                .then((Answer<List<TblInternalPerson>>) invocation -> {
+                    Object[] args = invocation.getArguments();
+                    return (List<TblInternalPerson>) args[0];
+                });
+
+
+        ldapUserService.synchronizeLDAP();
+    }
+
+    @Test
+    public void shouldSynchronizeLDAPRunThrou2() {
+        List<TblInternalPerson> internalPeople = MockDataHelper.mockTblInternalPersonPage().getContent();
+        when( internalPersonRepository.findByUidNotNull() ).thenReturn(internalPeople);
+
+        // users are not found
+        when( ldapTemplate.search(any(LdapQuery.class), any(LdapUserAttributesMapper.class))).thenReturn( Lists.emptyList() );
+
+        List<RefCommunicationType> refCommunicationTypes = MockDataHelper.mockRefCommunicationTypeList();
+        Whitebox.setInternalState(ldapUserService, "mailId", MAIL_ID);
+        Whitebox.setInternalState(ldapUserService, "telephoneNumberId", TEL_ID);
+        refCommunicationTypes.get(1).setId(TEL_ID);
+        refCommunicationTypes.get(2).setId(MAIL_ID);
+        when( communicationTypeRepository.findAll()).thenReturn(refCommunicationTypes);
+
+        ldapUserService.synchronizeLDAP();
+    }
+
+    @Test
+    public void shouldFindExistingAndNotExistingLdapUsers1() throws Exception {
+        List<TblInternalPerson> internalPeople = MockDataHelper.mockTblInternalPersonPage().getContent();
+        List<LdapUser> ldapUsers = new ArrayList<>();
+        List<TblInternalPerson> allNotExistingLdapUsers = new ArrayList<>();
+
+        List<LdapUser> ldapUserList = new ArrayList<>(1);
+        LdapUser ldapUser = MockDataHelper.mockLdapUser();
+        ldapUser.setUid(internalPeople.get(0).getUid());
+        ldapUserList.add( ldapUser );
+        // users are always found
+        when( ldapTemplate.search(any(LdapQuery.class), any(LdapUserAttributesMapper.class))).thenReturn( ldapUserList );
+
+        Whitebox.invokeMethod(ldapUserService, "findExistingAndNotExistingLdapUsers",
+                internalPeople, ldapUsers, allNotExistingLdapUsers);
+
+        assertEquals( internalPeople.size(), ldapUsers.size());
+        assertEquals( ldapUser, ldapUsers.get(0));
+        assertEquals( ldapUser, ldapUsers.get(1));
+    }
+
+    @Test
+    public void shouldFindExistingAndNotExistingLdapUsers2() throws Exception {
+        List<TblInternalPerson> internalPeople = MockDataHelper.mockTblInternalPersonPage().getContent();
+        List<LdapUser> ldapUsers = new ArrayList<>();
+        List<TblInternalPerson> allNotExistingLdapUsers = new ArrayList<>();
+
+        // users are not found
+        when( ldapTemplate.search(any(LdapQuery.class), any(LdapUserAttributesMapper.class))).thenReturn( Lists.emptyList() );
+
+        Whitebox.invokeMethod(ldapUserService, "findExistingAndNotExistingLdapUsers",
+                internalPeople, ldapUsers, allNotExistingLdapUsers);
+
+        assertEquals( 0, ldapUsers.size());
+    }
+
+
+    @Test
+    public void shouldFindExistingAndNotExistingLdapUsers3() throws Exception {
+        List<TblInternalPerson> internalPeople = MockDataHelper.mockTblInternalPersonPage().getContent();
+        List<LdapUser> ldapUsers = new ArrayList<>();
+        List<TblInternalPerson> allNotExistingLdapUsers = new ArrayList<>();
+
+        List<LdapUser> ldapUserList = new ArrayList<>(1);
+        LdapUser ldapUser = MockDataHelper.mockLdapUser();
+        ldapUser.setUid(internalPeople.get(0).getUid());
+        ldapUserList.add( ldapUser );
+        ldapUserList.add( new LdapUser());
+        // too much users are found
+        when( ldapTemplate.search(any(LdapQuery.class), any(LdapUserAttributesMapper.class))).thenReturn( ldapUserList );
+
+        Whitebox.invokeMethod(ldapUserService, "findExistingAndNotExistingLdapUsers",
+                internalPeople, ldapUsers, allNotExistingLdapUsers);
+
+        assertEquals( 0, ldapUsers.size());
+    }
+
+}
diff --git a/src/test/java/org/eclipse/openk/contactbasedata/support/MockDataHelper.java b/src/test/java/org/eclipse/openk/contactbasedata/support/MockDataHelper.java
index 54e216e..bde9bac 100644
--- a/src/test/java/org/eclipse/openk/contactbasedata/support/MockDataHelper.java
+++ b/src/test/java/org/eclipse/openk/contactbasedata/support/MockDataHelper.java
@@ -364,8 +364,9 @@
         ct2.setDescription("Mobil");
         ct2.setType("Mobil");
         RefCommunicationType ct3 = mockRefCommunicationType();
-        ct3.setDescription("Pers�nlich");
-        ct3.setType("Pers�nlich");
+        ct3.setDescription("E-Mail");
+        ct3.setType("E-Mail");
+        ct3.setTypeEmail(true);
 
         List<RefCommunicationType> listCt = new ArrayList<>();
         listCt.add(ct1);
@@ -725,4 +726,26 @@
         return list;
     }
 
+    public static LdapUser mockLdapUser() {
+        LdapUser ldapUser = new LdapUser();
+        ldapUser.setUid( UUID.randomUUID().toString() );
+        ldapUser.setFirstName("Ludwig");
+        ldapUser.setLastName("Lumpensammler");
+        ldapUser.setMail("ll@lumpi.de");
+
+        return ldapUser;
+    }
+
+    public static List<LdapUser> mockLdapUsers() {
+        List<LdapUser> list = new ArrayList<>();
+        LdapUser ldapUser2 = new LdapUser();
+        ldapUser2.setUid( UUID.randomUUID().toString() );
+        ldapUser2.setFirstName("Karl");
+        ldapUser2.setLastName("Kleinfink");
+        ldapUser2.setTelephoneNumber("99887766");
+        list.add( mockLdapUser() );
+        list.add( ldapUser2 );
+        return list;
+    }
+
 }