PageRenderTime 114ms CodeModel.GetById 100ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/xivo/ldap/AbstractLdapSynchronizer.java

https://gitlab.com/gesnaud/xivo-lib-ldap
Java | 252 lines | 230 code | 22 blank | 0 comment | 55 complexity | e051dcd62aa28425d29c1dd2dc7df905 MD5 | raw file
  1package xivo.ldap;
  2
  3import java.io.FileInputStream;
  4import java.io.FileNotFoundException;
  5import java.io.IOException;
  6import java.sql.SQLException;
  7import java.util.Arrays;
  8import java.util.List;
  9import java.util.logging.Level;
 10import java.util.logging.LogManager;
 11import java.util.logging.Logger;
 12
 13import javax.naming.NamingException;
 14
 15import org.apache.commons.cli.ParseException;
 16
 17import xivo.ldap.asterisk.AsteriskManager;
 18import xivo.ldap.configuration.ConfigLoader;
 19import xivo.ldap.configuration.Configuration;
 20import xivo.ldap.configuration.ExitCodes;
 21import xivo.ldap.ldapconnection.LDAPConnector;
 22import xivo.ldap.xivoconnection.EmptyContextException;
 23import xivo.ldap.xivoconnection.NumberOutOfContextException;
 24import xivo.ldap.xivoconnection.XivoConnector;
 25import xivo.restapi.connection.WebServicesException;
 26import xivo.restapi.model.CtiConfiguration;
 27import xivo.restapi.model.CtiProfile;
 28import xivo.restapi.model.User;
 29
 30import com.google.inject.Guice;
 31import com.google.inject.Inject;
 32import com.google.inject.Injector;
 33
 34public abstract class AbstractLdapSynchronizer {
 35
 36    protected Configuration config = ConfigLoader.getConfig();
 37    @Inject
 38    protected AbstractDeltaGenerator deltaGenerator;
 39    @Inject
 40    protected XivoConnector xivoConnector;
 41    @Inject
 42    protected LDAPConnector ldapConnector;
 43    @Inject
 44    protected Initializer initializer;
 45    @Inject
 46    protected AsteriskManager asteriskManager;
 47    protected List<User> xivoUsers;
 48    protected List<User> ldapUsers;
 49    protected static Logger logger;
 50
 51    public static void start(Class<? extends AbstractLDAPModule> moduleClass, String[] args) {
 52        initiateLogger();
 53        ParsingResult parsing = null;
 54        try {
 55            parsing = new ArgumentParser().parse(args);
 56        } catch (ParseException e) {
 57            logger.log(Level.SEVERE, "Error parsing the parameters : " + Arrays.toString(args), e);
 58            System.exit(ExitCodes.WRONG_CLI_PARAMETERS.ordinal());
 59        }
 60        AbstractLDAPModule module = getModuleInstance(moduleClass, parsing);
 61        Injector injector = Guice.createInjector(module);
 62        AbstractLdapSynchronizer synchronizer = injector.getInstance(AbstractLdapSynchronizer.class);
 63        synchronizer.setUp();
 64        try {
 65            synchronizer.retrieveUsers();
 66        } catch (WebServicesException e) {
 67            logger.log(Level.SEVERE, "Error with restapi when retrieving the users", e);
 68            System.exit(ExitCodes.REST_API_ERROR.ordinal());
 69        } catch (SQLException e) {
 70            logger.log(Level.SEVERE, "Error with postgres when retrieving the users", e);
 71            System.exit(ExitCodes.REST_API_ERROR.ordinal());
 72        } catch (NamingException e) {
 73            logger.log(Level.SEVERE, "Error with the LDAP when retrieving the users", e);
 74            System.exit(ExitCodes.REST_API_ERROR.ordinal());
 75        } catch (IOException e) {
 76            logger.log(Level.SEVERE, "Error when retrieving the users", e);
 77            System.exit(ExitCodes.REST_API_ERROR.ordinal());
 78        }
 79        try {
 80            if (parsing.isInitiatialization())
 81                synchronizer.initialize();
 82            else
 83                synchronizer.synchronize();
 84        } catch (WebServicesException e) {
 85            logger.log(Level.SEVERE, "Error with restapi when performing the synchronization", e);
 86        } catch (SQLException e) {
 87            logger.log(Level.SEVERE, "Error with postgres when performing the synchronization", e);
 88        } catch (IOException e) {
 89            logger.log(Level.SEVERE, "Error when performing the synchronization", e);
 90        }
 91    }
 92
 93    private static void initiateLogger() {
 94        try {
 95            FileInputStream configFile = new FileInputStream("config/logging.properties");
 96            LogManager.getLogManager().readConfiguration(configFile);
 97            configFile.close();
 98        } catch (FileNotFoundException e) {
 99            System.err.println("Could not find the logging configuration file, exiting.");
100            System.exit(ExitCodes.LOG_CONFIGURATION_ERROR.ordinal());
101        } catch (IOException e) {
102            System.err.println("Could not read the logging configuration file, exiting.");
103            System.exit(ExitCodes.LOG_CONFIGURATION_ERROR.ordinal());
104        }
105        logger = Logger.getLogger(AbstractLdapSynchronizer.class.getName());
106    }
107
108    private static AbstractLDAPModule getModuleInstance(Class<? extends AbstractLDAPModule> moduleClass,
109            ParsingResult parsing) {
110        AbstractLDAPModule module = null;
111        try {
112            module = moduleClass.getConstructor(boolean.class).newInstance(parsing.isDryRun());
113        } catch (Exception e) {
114            logger.log(Level.SEVERE, "Error instantiating " + moduleClass.getName()
115                    + ", did you define a constructor with a single boolean parameter ?", e);
116            System.exit(ExitCodes.CODE_STRUCTURE_ERROR.ordinal());
117        }
118        return module;
119    }
120
121    protected abstract void setUp();
122
123    protected abstract void performSpecificActions();
124
125    private void retrieveUsers() throws IOException, WebServicesException, SQLException, NamingException {
126        xivoUsers = xivoConnector.getAllUsers();
127        ldapUsers = ldapConnector.getUsers();
128    }
129
130    protected void initialize() throws IOException, WebServicesException, SQLException {
131        initializer.initialize(xivoUsers, ldapUsers);
132        xivoConnector.disableLiveReload();
133        for (User u : initializer.getUsersToUpdate())
134            xivoConnector.updateUser(u);
135        xivoConnector.enableLiveReload();
136    }
137
138    protected void synchronize() throws IOException, WebServicesException, SQLException {
139        deltaGenerator.generateDelta(xivoUsers, ldapUsers);
140        xivoConnector.disableLiveReload();
141        performCreations();
142        performUpdates();
143        performDeletions();
144        performLdapUpdates();
145        performSpecificActions();
146        xivoConnector.enableLiveReload();
147        asteriskManager.reloadCore();
148    }
149
150    protected void performLdapUpdates() {
151        List<User> ldapUpdates = deltaGenerator.getUpdatesToLdap();
152        if (config.updateLdap()) {
153            ldapConnector.updateUsers(ldapUpdates, config.getUpdatedLdapFields());
154        }
155    }
156
157    protected void performDeletions() throws IOException {
158        for (User u : deltaGenerator.getUsersToDelete()) {
159            try {
160                if (config.deleteVoicemails())
161                    xivoConnector.deleteVoicemailForUser(u);
162                if (config.deleteLines())
163                    xivoConnector.deleteLineForUser(u);
164                if (config.deleteIncalls())
165                    xivoConnector.deleteIncallForUser(u);
166                if (config.deleteUsers())
167                    xivoConnector.deleteUser(u);
168            } catch (WebServicesException | SQLException e) {
169                logger.log(Level.SEVERE, "Error deleting the user " + u, e);
170            }
171        }
172        for(User u: deltaGenerator.getUsersToUpdate()) {
173            try {
174                User original = xivoConnector.getUser(u.getId());
175                if(config.deleteLines() && u.getLine() == null && original.getLine() != null)
176                    xivoConnector.deleteLineForUser(original);
177                if(config.deleteVoicemails() && u.getVoicemail() == null && original.getVoicemail() != null)
178                    xivoConnector.deleteVoicemailForUser(original);
179                if(config.deleteIncalls() && u.getIncomingCall() == null && original.getIncomingCall() != null)
180                    xivoConnector.deleteIncallForUser(original);
181            } catch (WebServicesException | SQLException e) {
182                logger.log(Level.SEVERE, "Error deleting a subobject for user " + u, e);
183            }
184        }
185    }
186
187    protected void performUpdates() throws IOException {
188        for (User u : deltaGenerator.getUsersToUpdate()) {
189            try {
190                if (config.updateUsers()) {
191                    xivoConnector.updateUser(u);
192                }
193                if (config.updateLines()) {
194                    xivoConnector.updateLineForUser(u);
195                }
196                if (config.updateVoicemails()) {
197                    xivoConnector.updateVoicemailForUser(u);
198                }
199                if (config.updateIncalls()) {
200                    xivoConnector.updateIncallForUser(u);
201                }
202            } catch (WebServicesException | SQLException | EmptyContextException | NumberOutOfContextException e) {
203                logger.log(Level.SEVERE, "Error deleting the user " + u, e);
204            }
205        }
206
207    }
208
209    protected void performCreations() throws IOException {
210        List<User> usersToCreate = deltaGenerator.getUsersToCreate();
211        List<User> usersToUpdate = deltaGenerator.getUsersToUpdate();
212        setDefaultCtiConfig(usersToCreate);
213        for (User u : usersToCreate) {
214            try {
215                if (config.createUsers())
216                    xivoConnector.createUser(u);
217                if (config.createLines())
218                    xivoConnector.createLineForUser(u);
219                if (config.createVoicemails())
220                    xivoConnector.createVoicemailForUser(u);
221                if (config.createIncalls())
222                    xivoConnector.createIncallForUser(u);
223            } catch (WebServicesException | EmptyContextException | NumberOutOfContextException | SQLException e) {
224                logger.log(Level.SEVERE, "Error creating the user " + u, e);
225            }
226        }
227
228        for (User user : usersToUpdate) {
229            try {
230                if (config.createLines() && user.getLine() != null && user.getLine().getLineId() == null)
231                    xivoConnector.createLineForUser(user);
232                if (config.createVoicemails() && user.getVoicemail() != null && user.getVoicemail().getId() == null)
233                    xivoConnector.createVoicemailForUser(user);
234            } catch (WebServicesException e) {
235                logger.log(Level.SEVERE, "Error updating the user " + user, e);
236            }
237        }
238    }
239
240    private void setDefaultCtiConfig(List<User> usersToCreate) throws IOException {
241        CtiProfile defaultProfile = xivoConnector.getDefaultCtiProfile();
242        CtiConfiguration defaultCtiConfig = new CtiConfiguration(true, defaultProfile);
243        for (User user : usersToCreate) {
244            if (user.getUsername() != null && user.getPassword() != null) {
245                if (user.getCtiConfiguration() == null)
246                    user.setCtiConfiguration(defaultCtiConfig);
247                else if (user.getCtiConfiguration().getCtiProfile() == null)
248                    user.getCtiConfiguration().setCtiProfile(defaultProfile);
249            }
250        }
251    }
252}