--- /dev/null
+package com.pentila.entSavoie.userPurge;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import javax.naming.Binding;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+
+import com.liferay.portal.kernel.dao.orm.QueryUtil;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.kernel.util.PropsKeys;
+import com.liferay.portal.model.Organization;
+import com.liferay.portal.model.User;
+import com.liferay.portal.security.ldap.PortalLDAPUtil;
+import com.liferay.portal.service.CompanyLocalServiceUtil;
+import com.liferay.portal.service.UserLocalServiceUtil;
+import com.liferay.portal.util.PrefsPropsUtil;
+import com.liferay.portlet.documentlibrary.folder.service.DLFolderLocalServiceUtil;
+import com.liferay.portlet.documentlibrary.model.DLFileEntry;
+import com.liferay.portlet.documentlibrary.model.DLFolder;
+import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
+import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
+import com.pentila.entSavoie.cahierDeTexte.model.EventCDT;
+import com.pentila.entSavoie.cahierDeTexte.model.EventSTSRef;
+import com.pentila.entSavoie.cahierDeTexte.service.EventCDTLocalServiceUtil;
+import com.pentila.entSavoie.cahierDeTexte.service.EventSTSRefLocalServiceUtil;
+import com.pentila.entSavoie.cartable.model.DlLink;
+import com.pentila.entSavoie.cartable.service.CasierEntryLocalServiceUtil;
+import com.pentila.entSavoie.cartable.service.DlLinkLocalServiceUtil;
+import com.pentila.entSavoie.casier.Constants;
+import com.pentila.entSavoie.directory.OrganizationFinderServiceUtil;
+import com.pentila.entSavoie.gestionMenus.model.PronoteLink;
+import com.pentila.entSavoie.gestionMenus.service.PronoteLinkLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.model.InternalFolderMessage;
+import com.pentila.entSavoie.internalMessaging.model.InternalMessage;
+import com.pentila.entSavoie.internalMessaging.service.InternalFolderMessageLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.service.InternalMessageLocalServiceUtil;
+import com.pentila.entSavoie.userManagement.service.LDAPMappingLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.model.UserContact;
+import com.pentila.entSavoie.userProperties.service.NotifyConfigLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.service.UserContactLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.service.UserMailSynchronisationLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.service.UserPropertiesLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.service.UserRelationshipLocalServiceUtil;
+
+public class UserPurgeImpl {
+
+ private static Log logger = LogFactoryUtil.getLog(UserPurgeImpl.class);
+
+ /**
+ * Purges all expired users in LDAP (ENTValidAccount = 2)
+ * @return the list of purged userIds
+ */
+ public static List<Long> purgeExpiredUsers (long companyId) {
+
+ logger.info("Start purgeExpiredUsers");
+ List<Long> purgedUserList = new ArrayList<Long>();
+
+ // Fetch users in LDAP with ENTPersonJointure = 2
+ SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 0, null, false, false);
+ long todayDate = getTodayDate();
+ String invalidUsersToDeleteSearchFilter = "(ENTValidAccount=2)";
+
+ NamingEnumeration<SearchResult> invalidUsersEnum = null;
+ String usersBaseDN = "";
+ try {
+ usersBaseDN = "ou=people,"+PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN);
+ } catch (SystemException e) {
+ logger.error("Could not get the users base dn or the user filter");
+ e.printStackTrace();
+ }
+ if (usersBaseDN.equals("")) {
+ logger.error("Could not get the users base dn or the user filter");
+ return null;
+ }
+ try {
+ invalidUsersEnum = PortalLDAPUtil.doContextSearch(companyId, usersBaseDN, invalidUsersToDeleteSearchFilter, cons);
+ } catch (Exception e) {
+ e.printStackTrace();
+ logger.info("Could not perform the LDAP context search for invalid users.");
+ return null;
+ }
+
+ if (invalidUsersEnum == null) {
+ logger.info("Could not perform the LDAP context search for invalid users.");
+ return null;
+ }
+
+ int count = 0;
+ while (invalidUsersEnum.hasMoreElements()) {
+
+ logger.info("Processing user deletion number "+count);
+
+ SearchResult result = invalidUsersEnum.nextElement();
+ if (result == null) {
+ continue;
+ }
+ Attributes attrs = result.getAttributes();
+ if (attrs == null) {
+ logger.info("No attributes for this user, skipping ...");
+ continue;
+ }
+
+ // Get ENTExpireAccount value
+ String entExpireAccount = getAttributeValue(attrs, "ENTExpireAccount");
+ if (entExpireAccount == null) {
+ logger.info("entExpireAccount cannot be fetched => skipping ...");
+ continue;
+ }
+ long expireDate = Integer.parseInt(entExpireAccount);
+
+ // Get uid value
+ String uid = getAttributeValue(attrs, "uid");
+ if (uid == null) {
+ logger.info("uid cannot be fetched => skipping ...");
+ continue;
+ }
+
+ // Build dn
+// String userDn = "";
+// try {
+// userDn = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_USERS_DN);
+// } catch (SystemException e1) {
+// logger.info("Could not get ldap.users.dn variable in portal-ext.properties");
+// e1.printStackTrace();
+// continue;
+// }
+ String dn = "uid="+uid+","+usersBaseDN;
+ logger.info("Deleting user with dn = "+dn);
+
+ // Get ENTPersonLogin attribute
+ String entPersonLogin = getAttributeValue(attrs, "ENTPersonLogin");
+ if (entPersonLogin == null) {
+ logger.info("Could not get ENTPersonLogin attribute in result.");
+ continue;
+ }
+
+ // Manage inconsistent state of users marked for deletion but with an expiration date in the future
+ if (expireDate > todayDate) {
+ logger.info("Error with dn "+dn+" (login="+entPersonLogin+") with ENTValidAccount=2 but ENTExpireAccount > today : "+entExpireAccount);
+ continue;
+ }
+
+ // Run the deletion in LDAP
+ try {
+ PortalLDAPUtil.delete(companyId, dn);
+ logger.info("User with dn="+dn+" deleted in LDAP.");
+ } catch (Exception e) {
+ e.printStackTrace();
+ logger.error("Failed to delete dn "+dn+" in LDAP");
+ }
+
+ // Get userId
+ User user = null;
+ try {
+ user = UserLocalServiceUtil.getUserByScreenName(companyId, entPersonLogin);
+ } catch (Exception e) {
+ logger.info("Could not find userId for entPersonLogin "+entPersonLogin);
+ e.printStackTrace();
+ }
+ if (user != null) {
+ long userId = user.getUserId();
+
+ // The deletion in DB
+ purgeUserInDB(userId);
+ logger.info("User with dn="+dn+" deleted in DB.");
+
+ purgedUserList.add(userId);
+ } else {
+ logger.info("Could not find userId for entPersonLogin "+entPersonLogin);
+ }
+ count ++;
+ }
+ logger.info("END user purge : deleted "+count+ " users");
+ return purgedUserList;
+ }
+
+
+ /**
+ * Get the attribute value from the list of attributes
+ * @param attrs
+ * @param attributeName
+ * @return
+ */
+ private static String getAttributeValue(Attributes attrs, String attributeName) {
+ String res = null;
+ try {
+ if (attrs.get(attributeName) != null && attrs.get(attributeName).get() != null) {
+ res = attrs.get(attributeName).get().toString();
+ }
+ } catch (NamingException e1) {
+ logger.debug("Could not get "+attributeName+" attribute");
+ e1.printStackTrace();
+ }
+ return res;
+ }
+
+
+ /**
+ * Returns the today date (in number of days since 01/01/1970)
+ * @return
+ */
+ private static long getTodayDate() {
+ Date today = new Date();
+ return today.getTime() / 86400000;
+ }
+
+
+ /**
+ * Deletes the user in the LDAP
+ * @param companyId
+ * @param dn
+ */
+ public static boolean purgeUserInLDAP (long companyId, String screenName) {
+
+ logger.info("Cleaning user login "+screenName+" in LDAP...");
+ String dn = "";
+ try {
+ Binding b = PortalLDAPUtil.getUser(companyId, screenName);
+ if(b == null){
+ logger.error("Binding is null");
+ return false;
+ }
+ String[] attrs2fetch = {"uid"};
+ Attributes attrs = PortalLDAPUtil.doContextAttributes(companyId, PortalLDAPUtil.getNameInNamespace(companyId, b), attrs2fetch);
+
+ String uid = getAttributeValue(attrs, "uid");
+
+ // Build dn
+ String userDn = "";
+ try {
+ userDn = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_USERS_DN);
+ } catch (SystemException e) {
+ logger.info("Could not get ldap.users.dn variable in portal-ext.properties");
+ return false;
+ }
+ dn = "uid="+uid+","+userDn;
+
+ } catch(Exception e){
+ e.printStackTrace();
+ return false;
+ }
+
+ if (dn.equals("")) {
+ logger.error("Could not get dn from the screenName in LDAP");
+ return false;
+ }
+
+ try {
+ logger.info("About to delete user in LDAP with dn = "+dn);
+ PortalLDAPUtil.delete(companyId, dn);
+ } catch (Exception e) {
+ e.printStackTrace();
+ logger.error("Failed to delete dn "+dn);
+ return false;
+ }
+ logger.info("Deleted user login "+screenName+" in LDAP (dn="+dn+")");
+ return true;
+ }
+
+
+ /**
+ * Cleans up all data related to a given userId (both DB and LDAP)
+ * @param userId
+ */
+ public static boolean purgeUserInDB(long userId) {
+
+ logger.info("Cleaning up user id "+userId+" in DB ...");
+ initUserCounts();
+
+ // 1. Cleaning messaging
+ cleanupMessaging(userId);
+
+ // 2. Cleaning DLFileEntries
+ cleanupDLFileEntries(userId);
+ //cleanupDLFolders(userId);
+
+ // 3. Cleaning CDT events
+ cleanupCDTEvents(userId);
+
+ // 4. Cleanup notify config
+ cleanupNotifyConfig(userId);
+
+ // 5. Cleanup user mail synchronisation
+ cleanupMailSynchronisation(userId);
+
+ // 6. Cleanup user properties
+ cleanupUserProperties(userId);
+
+ // 7. Cleanup user relationships
+ cleanupUserRelationships(userId);
+
+ // 8. Cleanup dropbox entries
+ cleanupDropboxEntries(userId);
+
+ // 9. Cleanup LDAPMapping
+ cleanupLDAPMapping(userId);
+
+ // 10. Cleanup user contact
+ cleanupUserContact(userId);
+
+ // 10. Cleanup Pronote links
+ cleanupPronoteLinks(userId);
+
+ // Delete user
+ logger.info("Deleting user itself in DB ...");
+ try {
+ UserLocalServiceUtil.deleteUser(userId);
+ } catch (Exception e) {
+ logger.error("Could not delete user of user id "+userId);
+ return false;
+ }
+
+ printUserReport(userId);
+ return true;
+ }
+
+ /**
+ * Clean up internal messaging for userId
+ * @param userId
+ */
+ private static void cleanupMessaging(long userId) {
+
+ logger.info("Cleaning internal messages for user "+userId+" ...");
+
+ User user = null;
+ try {
+ user = UserLocalServiceUtil.getUser(userId);
+ } catch (Exception e1) {
+ logger.error("Could not find user with userId = "+userId);
+ }
+
+ try {
+ if (user == null || user.getGroup() == null) {
+ logger.error("UserId "+userId+" has no group associated.");
+ return;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ // Get SENDING BOX dlfolder
+ DLFolder sendingBox = null;
+ try {
+ sendingBox = DLFolderLocalServiceUtil.getFolder(user.getGroup().getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.SENDING_BOX_FOLDER_NAME);
+ } catch (Exception exc) {
+ logger.error("Could not get sending box for user "+userId);
+ return;
+ }
+ if (sendingBox == null) {
+ logger.error("Could not get sending box for user "+userId);
+ return;
+ }
+ logger.info("Sending box folderid is "+sendingBox.getFolderId());
+
+ List<InternalFolderMessage> folderMessageList;
+ try {
+ folderMessageList = InternalFolderMessageLocalServiceUtil.getUserFolderMessages(userId);
+ if (folderMessageList != null) {
+
+ // Loop over user's folders
+ for (InternalFolderMessage folder : folderMessageList) {
+ logger.debug("Folder name = "+folder.getFolderName()+", id="+folder.getFolderMessageId());
+
+
+
+ // Delete messages + internal receivers + attached files + attached files folders
+ try {
+ List<InternalMessage> messageList = InternalMessageLocalServiceUtil.getMessagesByFolder(folder.getFolderMessageId(), userId);
+ if (messageList != null) {
+ for (InternalMessage message : messageList) {
+
+ if (message.getFolderMessageId() == sendingBox.getFolderId()) {
+ logger.info("Do not delete message "+message.getMessageId()+" because in user's sending box");
+ continue;
+ }
+ try {
+ InternalMessageLocalServiceUtil.deleteMessageAndDependencies(message);
+ logger.debug("Deleted message id "+message.getMessageId()+ "(subject="+message.getMessageSubject()+")");
+ userNbMessagesSuccess++;
+ } catch (Exception e) {
+ userNbMessagesError++;
+ continue;
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.info("Error : could not get all messages by folderId "+folder.getFolderMessageId());
+ }
+ }
+ }
+ } catch (SystemException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+
+ /**
+ * Clean up DL file entries for given userId
+ * @param userId
+ */
+ private static void cleanupDLFolders(long userId) {
+
+ logger.info("Cleaning up DLFolders for user id "+userId+" ...");
+
+ User user = getUser(userId);
+
+ try {
+ List<DLFolder> dlFolderList = DLFolderLocalServiceUtil.getFolders(user.getGroupId(), 0, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
+ for (DLFolder dlFolder : dlFolderList) {
+ if (dlFolder.getName().equals(Constants.DROP_BOX_FOLDER_NAME) || dlFolder.getName().equals(Constants.SCHOOL_BAG_FOLDER_NAME)) {
+ logger.info("Deleting folder "+dlFolder.getName());
+ DLFolderLocalServiceUtil.deleteFolder(dlFolder.getFolderId());
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Unable to get user's DLFolders", e);
+ }
+
+ }
+
+ /**
+ * Clean up DL file entries for given userId
+ * @param userId
+ */
+ private static void cleanupDLFileEntries(long userId) {
+
+ logger.info("Cleaning up DLFileEntries for user id "+userId+" ...");
+
+ User user = getUser(userId);
+
+ // Get DL entries for the user
+ List<DLFileEntry> fileList = new ArrayList<DLFileEntry>();
+ try {
+ fileList = DLFileEntryLocalServiceUtil.getGroupFileEntries(user.getGroup().getGroupId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
+ } catch (Exception e) {
+ logger.error("Could not get group file entries for userId "+userId);
+ e.printStackTrace();
+ }
+
+ if (fileList == null) {
+ logger.error("Could not get group file entries for userId "+userId);
+ return;
+ }
+
+ // Get SENDING BOX and IM_BOX dlfolders
+ // Because we do not want to delete sent files and internalmessage PJfolders
+ DLFolder sendingBox = null;
+ DLFolder imBox = null;
+ try {
+ sendingBox = DLFolderLocalServiceUtil.getFolder(user.getGroup().getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.SENDING_BOX_FOLDER_NAME);
+ imBox = DLFolderLocalServiceUtil.getFolder(user.getGroup().getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.IM_BOX_FOLDER_NAME);
+ } catch (Exception exc) {
+ logger.error("Could not get sending box or im box for user "+userId);
+ }
+
+ // Loop over DL files
+ for (DLFileEntry dlFile : fileList) {
+ logger.info("Deleting DLFileEntry "+dlFile.getTitle()+" (id="+dlFile.getFileEntryId()+", folderId="+dlFile.getFolderId()+")");
+
+ // If file is in user's sending box => do not delete it
+ if (sendingBox != null && dlFile.getFolderId() == sendingBox.getFolderId()) {
+ logger.info("This file "+dlFile.getFileEntryId()+" is in the user's sending box => do not delete it");
+ userNbSourceLinkDLFiles++;
+ continue;
+ }
+
+ // If file is in a PJ folder that is in user's im box => do not delete it
+ DLFolder fileFolder = null;
+ try {
+ fileFolder = DLFolderLocalServiceUtil.getDLFolder(dlFile.getFolderId());
+ } catch (Exception e) {
+ }
+ if (fileFolder != null && imBox != null && fileFolder.getParentFolderId() == imBox.getFolderId()) {
+ logger.info("This file "+dlFile.getFileEntryId()+" is in the user's im box => do not delete it");
+ userNbSourceLinkDLFiles++;
+ continue;
+ }
+
+ // If this file is a source link => do not delete
+ try {
+ List<DlLink> dlSourceLinkList = DlLinkLocalServiceUtil.getDlFileLinkBySourceId(dlFile.getFileEntryId());
+ if (dlSourceLinkList != null && !dlSourceLinkList.isEmpty()) {
+ logger.info("Do not delete file id "+dlFile.getFileEntryId()+" because it is a source link for "+dlSourceLinkList.size()+" targets.");
+ userNbSourceLinkDLFiles++;
+ continue;
+ } else {
+ logger.info("No source link for dl file entry "+dlFile.getFileEntryId()+".");
+ }
+ } catch (SystemException e) {
+ logger.error("Could not get source link for dlFileEntry "+dlFile.getFileEntryId());
+ }
+
+ // If this file is a target link => delete the link and delete the file
+ DlLink dlTargetLink = null;
+ try {
+ dlTargetLink = DlLinkLocalServiceUtil.getDlFileLinkByTarget(dlFile.getFileEntryId());
+ DlLinkLocalServiceUtil.deleteDlLink(dlTargetLink);
+ logger.info("Deleting target link");
+ userNbTargetLinkDLFiles++;
+ } catch (Exception e) {
+ }
+
+ // Delete the file itself in both DB and File System
+ try {
+ DLFileEntryLocalServiceUtil.deleteDLFileEntry(dlFile);
+ logger.info("Deleted file entry "+dlFile.getFileEntryId()+" in DB and FS OK");
+ } catch (SystemException e) {
+ logger.error("Could not delete dlFileEntry "+dlFile.getFileEntryId());
+ userNbDLFilesError++;
+ e.printStackTrace();
+ continue;
+ }
+
+ }
+
+ }
+
+
+ /**
+ * Clean up CDT events for given userId
+ * @param userId
+ */
+ private static void cleanupCDTEvents(long userId) {
+
+ logger.info("Cleaning up CDT events for user id "+userId+" ...");
+ List<EventCDT> eventCDTList = EventCDTLocalServiceUtil.getEventCDTbyCreator(userId);
+ if (eventCDTList != null) {
+ for (EventCDT event : eventCDTList) {
+ try {
+ EventCDTLocalServiceUtil.deleteAttachFilesToEventCDT(userId, event.getEvtId());
+ } catch (Exception e) {
+ logger.error("Could not delete attach files of event id "+event.getEvtId());
+ }
+ try {
+ EventCDTLocalServiceUtil.deleteEvent(event); // Also delete the index
+ userNbEventsSuccess++;
+ } catch (Exception e) {
+ logger.error("Could not delete event id "+event.getEvtId());
+ userNbEventsError++;
+ }
+ }
+ }
+
+ User user;
+ try {
+ user = UserLocalServiceUtil.getUser(userId);
+ if (user != null) {
+ Organization etabRattachement = OrganizationFinderServiceUtil.getEtabRatachement(user);
+ if (etabRattachement != null) {
+ List<EventSTSRef> eventSTSRefList = EventSTSRefLocalServiceUtil.getEventSTSRefByEtabIdUserId(etabRattachement.getOrganizationId(), userId);
+ for (EventSTSRef eventSTS : eventSTSRefList) {
+ try {
+ EventSTSRefLocalServiceUtil.deleteEventSTSRef(eventSTS);
+ userNbEventsSuccess++;
+ } catch (Exception e) {
+ logger.error("Could not delete eventSTSRefs");
+ userNbEventsError++;
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Could not delete eventSTSRefs");
+ }
+
+ }
+
+ /**
+ * Clean up notify configuration for given userId
+ * @param userId
+ */
+ private static void cleanupNotifyConfig(long userId) {
+
+ logger.info("Cleaning notify configuration ...");
+ try {
+ NotifyConfigLocalServiceUtil.deleteNotifyConfigByUser(userId);
+ } catch (Exception e) {
+ logger.error("Could not delete the notify configuration for user id "+userId);
+ }
+
+ }
+
+ /**
+ * Clean up mail synchronization data for given userId
+ * @param userId
+ */
+ private static void cleanupMailSynchronisation(long userId) {
+
+ logger.info("Cleaning mail sychronisation ...");
+ try {
+ UserMailSynchronisationLocalServiceUtil.deleteUserMailSynchronisation(userId);
+ } catch (Exception e) {
+ logger.error("Could not delete the mail synchronisation for user id "+userId);
+ }
+
+ }
+
+ /**
+ * Clean up user properties for given userId
+ * @param userId
+ */
+ private static void cleanupUserProperties(long userId) {
+
+ logger.info("Cleaning user properties ...");
+ try {
+ UserPropertiesLocalServiceUtil.deleteUserPropertiesByUserId(userId);
+ } catch (Exception e) {
+ logger.error("Could not delete user properties for userid "+userId);
+ }
+
+ }
+
+ /**
+ * Clean up user relationships for given userId
+ * @param userId
+ */
+ private static void cleanupUserRelationships(long userId) {
+
+ logger.info("Cleaning user relationships ...");
+ try {
+ UserRelationshipLocalServiceUtil.deleteByFromUserId(userId);
+ userNbRelationshipsSuccess++;
+ } catch (Exception e) {
+ logger.error("Could not delete relationship with user id "+userId);
+ userNbRelationshipsError++;
+ }
+ try {
+ UserRelationshipLocalServiceUtil.deleteByToUserId(userId);
+ userNbRelationshipsSuccess++;
+ } catch (Exception e) {
+ logger.error("Could not delete relationship with user id "+userId);
+ userNbRelationshipsError++;
+ }
+
+ }
+
+
+ /**
+ * Clean up DL user groups for given userId
+ * @param userId
+ */
+ private static void cleanupDropboxEntries(long userId) {
+
+ logger.info("Cleaning user dropbox entries ...");
+
+ long companyId = 0;
+ try {
+ companyId = CompanyLocalServiceUtil.getCompanies().get(0).getCompanyId();
+ } catch (SystemException e) {
+ logger.error("Failed to get the companyId");
+ return;
+ }
+
+ try {
+ CasierEntryLocalServiceUtil.deleteByGroupId(companyId, getUser(userId).getGroup().getGroupId());
+ } catch (Exception e) {
+ logger.error("Failed to delete dropbox entries");
+ }
+
+ }
+
+
+ private static User getUser(long userId) {
+ User user = null;
+ try {
+ user = UserLocalServiceUtil.getUser(userId);
+ } catch (Exception e1) {
+ logger.error("Could not find user with userId = "+userId);
+ }
+
+ try {
+ if (user == null || user.getGroup() == null) {
+ logger.error("UserId "+userId+" has no group associated.");
+ return null;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return user;
+ }
+
+
+ private static void cleanupLDAPMapping(long userId) {
+
+ logger.info("Cleaning user LDAP Mapping ...");
+ try {
+ LDAPMappingLocalServiceUtil.deleteLDAPMapping(userId);
+ } catch (Exception e) {
+ logger.error("Failed to delete LDAPMapping");
+ }
+ }
+
+
+ private static void cleanupUserContact(long userId) {
+
+ logger.info("Cleaning user contact infos ...");
+ try {
+ UserContact userContact = UserContactLocalServiceUtil.getUserContactByUserId(userId);
+ UserContactLocalServiceUtil.deleteUserContact(userContact);
+ } catch (Exception e) {
+ logger.error("Failed to delete user contact infos");
+ }
+
+ }
+
+ private static void cleanupPronoteLinks(long userId) {
+
+ logger.info("Cleaning user pronote links ...");
+ try {
+ List<PronoteLink> pronoteLinks = PronoteLinkLocalServiceUtil.getUserPronoteLinks(userId);
+ if (pronoteLinks != null) {
+ for (PronoteLink pronoteLink : pronoteLinks) {
+ PronoteLinkLocalServiceUtil.deletePronoteLink(pronoteLink);
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Failed to delete user pronote links");
+ }
+
+ }
+
+// private static void initFileOutput() {
+// try {
+// FileWriter fw = new FileWriter(DEFAULT_OUTPUT_FILE_PATH+"_"+new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date())+".txt", true);
+// output = new BufferedWriter(fw);
+//
+// } catch (IOException e) {
+// logger.error("Could not open write buffer.");
+// e.printStackTrace();
+// }
+//
+// }
+//
+// /**
+// * Write a file path to output file (contains all file paths to delete further)
+// */
+// private static void writeFileOutput(String filePath) {
+// try {
+// output.write(filePath+"\n");
+// output.flush();
+// } catch (IOException e) {
+// logger.error("Could not write data into output file: "+filePath);
+// e.printStackTrace();
+// }
+// }
+
+
+ /**
+ * Prints a report for a given user
+ */
+ private static void printUserReport(long userId) {
+
+ StringBuilder str = new StringBuilder();
+ str.append("============================\n");
+ str.append("USER CLEANUP REPORT\n\n");
+ str.append("Cleanup for user "+userId+"\n");
+ str.append(" - "+userNbMessagesSuccess+" internal messages deleted\n");
+ str.append(" - "+userNbDLFilesSuccess+" DL files marked for deletion\n");
+ str.append(" - "+userNbTargetLinkDLFiles+" DL links deleted\n");
+ str.append(" - "+userNbEventsSuccess+" CDT events deleted\n");
+ str.append(" - "+userNbRelationshipsSuccess+" relationships deleted\n");
+
+ str.append("Errors:");
+ if (userNbMessagesError > 0) {
+ str.append(" - "+userNbMessagesError+" internal messages not deleted\n");
+ }
+ if (userNbDLFilesError > 0) {
+ str.append(" - "+userNbDLFilesError+" DL files not deleted\n");
+ }
+ if (userNbSourceLinkDLFiles > 0) {
+ str.append(" - "+userNbSourceLinkDLFiles+" DL files not deleted because source links\n");
+ }
+ if (userNbEventsError > 0) {
+ str.append(" - "+userNbEventsError+" CDT events not deleted\n");
+ }
+ if (userNbRelationshipsError > 0) {
+ str.append(" - "+userNbRelationshipsError+" relationships not deleted\n");
+ }
+ str.append("\n");
+ str.append("============================\n");
+
+ String userReport = str.toString();
+ logger.info("\n"+userReport);
+
+ }
+
+ /**
+ * Initiates all counts related to a given user
+ */
+ private static void initUserCounts() {
+ userNbMessagesSuccess = 0;
+ userNbMessagesError = 0;
+ userNbDLFilesSuccess = 0;
+ userNbDLFilesError = 0;
+ userNbSourceLinkDLFiles = 0;
+ userNbTargetLinkDLFiles = 0;
+ userNbEventsSuccess = 0;
+ userNbEventsError = 0;
+ userNbRelationshipsSuccess = 0;
+ userNbRelationshipsError = 0;
+ }
+
+ // Messaging
+ private static int userNbMessagesSuccess;
+ private static int userNbMessagesError;
+
+ // DL Files
+ private static int userNbDLFilesSuccess;
+ private static int userNbDLFilesError;
+ private static int userNbSourceLinkDLFiles;
+ private static int userNbTargetLinkDLFiles;
+
+ // CDT
+ private static int userNbEventsSuccess;
+ private static int userNbEventsError;
+
+ // Relationships
+ private static int userNbRelationshipsSuccess;
+ private static int userNbRelationshipsError;
+
+}