Java tutorial
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.bemis.portal.migration.customer.service.impl; import static com.bemis.portal.commons.constants.BemisPortalConstants.NOTFOUND_LAYOUTSET_PROTO_ID; import static com.bemis.portal.customer.constants.CustomerProfileConstants.BEMIS_CUSTOMER_ID; import static com.bemis.portal.customer.constants.CustomerProfileConstants.BEMIS_PARENT_ORGANIZATION; import static com.bemis.portal.customer.constants.CustomerProfileConstants.CUSTOMER_LOCATION_TYPE; import static com.bemis.portal.customer.constants.CustomerProfileConstants.PARENT_LOCATION_TYPE; import static com.liferay.expando.kernel.model.ExpandoTableConstants.DEFAULT_TABLE_NAME; import aQute.bnd.annotation.ProviderType; import com.bemis.portal.commons.service.BemisPortalService; import com.bemis.portal.migration.customer.exception.BemisCustomerSiteTemplateNotFoundException; import com.bemis.portal.migration.customer.model.CustomerOrg; import com.bemis.portal.migration.customer.model.CustomerUser; import com.bemis.portal.migration.customer.model.CustomerUserOrgRelation; import com.bemis.portal.migration.customer.service.base.CustomerMigrationLocalServiceBaseImpl; import com.liferay.expando.kernel.model.ExpandoBridge; import com.liferay.expando.kernel.model.ExpandoValue; import com.liferay.expando.kernel.service.ExpandoColumnLocalService; import com.liferay.expando.kernel.service.ExpandoTableLocalService; import com.liferay.expando.kernel.service.ExpandoValueLocalService; import com.liferay.portal.kernel.exception.NoSuchOrganizationException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.Contact; import com.liferay.portal.kernel.model.Group; import com.liferay.portal.kernel.model.ListTypeConstants; import com.liferay.portal.kernel.model.Organization; import com.liferay.portal.kernel.model.OrganizationConstants; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.security.auth.CompanyThreadLocal; import com.liferay.portal.kernel.service.ClassNameLocalService; import com.liferay.portal.kernel.service.ContactLocalService; import com.liferay.portal.kernel.service.CountryServiceUtil; import com.liferay.portal.kernel.service.OrganizationLocalService; import com.liferay.portal.kernel.service.RegionServiceUtil; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.UserLocalService; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.portal.spring.extender.service.ServiceReference; import com.liferay.sites.kernel.util.SitesUtil; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.time.StopWatch; /** * @author Abdullah Bushnaq */ @ProviderType public class CustomerMigrationLocalServiceImpl extends CustomerMigrationLocalServiceBaseImpl { @Override public Organization addOrganization(long userId, long parentOrganizationId, String name, String type, long regionId, long countryId, long statusId, String comments, boolean site, ServiceContext serviceContext, String bemisCustomerId, String bemisParentOrg) throws PortalException { Organization anOrganization = _organizationLocalService.addOrganization(userId, parentOrganizationId, name, type, regionId, countryId, statusId, comments, site, serviceContext); ExpandoBridge aBridge = anOrganization.getExpandoBridge(); aBridge.setAttribute(BEMIS_CUSTOMER_ID, bemisCustomerId); aBridge.setAttribute(BEMIS_PARENT_ORGANIZATION, bemisParentOrg); return anOrganization; } /** * Creates a Liferay User by using Customer User data. If a matching Liferay User * was found, that User is updated instead. * * Note: An update will not occur in the event of a change to both their * email address and screen name. A new user will be created in this case * instead. * * @param customerUser the customer user to be migrated. * @return the Liferay User created or updated. * @throws PortalException */ @Override public User addUser(CustomerUser customerUser, long companyId) { User liferayUser = fetchLiferayUser(customerUser, companyId); String email = customerUser.getEmail(); String firstName = customerUser.getFirstName(); String lastName = customerUser.getLastName(); String screenName = customerUser.getScreenName(); boolean male = customerUser.isMale(); long[] userOrganizationIdArray = getUserOrganizationsIds(email); if (liferayUser != null) { if (_log.isDebugEnabled()) { _log.debug(">>> Found Liferay user with screen name: " + screenName + ". Updating user instead."); } liferayUser.setEmailAddress(email); liferayUser.setFirstName(firstName); liferayUser.setLastName(lastName); liferayUser.setScreenName(screenName); _userLocalService.updateUser(liferayUser); Contact contact; try { contact = liferayUser.getContact(); contact.setEmailAddress(email); contact.setFirstName(firstName); contact.setLastName(lastName); contact.setMale(male); _contactLocalService.updateContact(contact); } catch (PortalException pe) { pe.printStackTrace(); } for (Long organizationId : userOrganizationIdArray) { userLocalService.addOrganizationUser(organizationId, liferayUser); } return liferayUser; } _calendar.setTime(new Date()); int birthDay = _calendar.get(Calendar.DATE); int birthMonth = _calendar.get(Calendar.MONTH); int birthYear = _calendar.get(Calendar.YEAR); try { liferayUser = _userLocalService.addUser(0, _bemisPortalService.getDefaultCompanyId(), false, "test", "test", false, screenName, customerUser.getEmail(), 0, null, LocaleUtil.getDefault(), firstName, null, lastName, 0, 0, male, birthMonth, birthDay, birthYear, null, null, userOrganizationIdArray, null, null, false, null); } catch (PortalException pe) { _log.error(">>> Error updating user: " + email, pe); } return liferayUser; } @Override public void migrateCustomers(Date lastModifiedDate, long companyId) throws BemisCustomerSiteTemplateNotFoundException { // Check that the required Bemis Customer Site is available long setPrototypeId = _bemisPortalService.getBemisCustomerSiteTemplateId(); if (setPrototypeId == NOTFOUND_LAYOUTSET_PROTO_ID) { throw new BemisCustomerSiteTemplateNotFoundException(); } if (_log.isInfoEnabled()) { _log.info(">>> Migrating as of " + lastModifiedDate.toString()); } migrateCustomerOrgs(lastModifiedDate, setPrototypeId); migrateCustomerUsersAsOfDate(lastModifiedDate, companyId); } protected Organization addOrganizationFromCustomer(long userId, CustomerOrg aCustomerOrgParent, long setPrototypeId, long parentOrganizationId) { String organizationType = OrganizationConstants.TYPE_ORGANIZATION; long statusId = ListTypeConstants.ORGANIZATION_STATUS_DEFAULT; long countryId = CountryServiceUtil.fetchCountryByA2(aCustomerOrgParent.getCountry()).getCountryId(); long regionId = RegionServiceUtil.fetchRegion(countryId, aCustomerOrgParent.getState()).getRegionId(); String bemisCustomerId = aCustomerOrgParent.getBemisCustomerId(); String bemisParentOrg = aCustomerOrgParent.getBemisParentId(); Organization anOrganization = null; String name = ""; // @TODO Custom fields need to be finalized from the customer profile // Only parent organizations get the default and the short name if (parentOrganizationId == OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID) { name = aCustomerOrgParent.getCustomerName(); organizationType = PARENT_LOCATION_TYPE; } else { name = aCustomerOrgParent.getCustomerName() + " - " + aCustomerOrgParent.getCity(); organizationType = CUSTOMER_LOCATION_TYPE; } try { anOrganization = _organizationLocalService.getOrganization(_bemisPortalService.getDefaultCompanyId(), name); if (_log.isDebugEnabled()) { _log.debug(">>> Organization with id [" + anOrganization.getOrganizationId() + "] already exists"); } } catch (NoSuchOrganizationException nsoe) { // If we are a new organization, let us add it. try { // Create an organization with a site anOrganization = addOrganization(userId, parentOrganizationId, name, organizationType, regionId, countryId, statusId, null, true, null, bemisCustomerId, bemisParentOrg); // Now we map the site to the customer template Group organizationGroup = anOrganization.getGroup(); SitesUtil.updateLayoutSetPrototypesLinks(organizationGroup, 0, setPrototypeId, true, true); _log.debug(">>> Created an Organization with id [" + anOrganization.getOrganizationId() + "]"); } catch (Exception pe) { _log.error(pe); } } catch (PortalException pe) { _log.error(">>> Error creating Organization for Customer [" + name + "]", pe); } return anOrganization; } /** * Attempts to retrieve a Liferay User that maps to the specified Customer * User by checking for a match by screen name or email address. * * @param customerUser * @param companyId * @return the matching Liferay User or null, if none is found. */ protected User fetchLiferayUser(CustomerUser customerUser, long companyId) { String screenName = customerUser.getScreenName(); String emailAddress = customerUser.getEmail(); User liferayUser = _userLocalService.fetchUserByScreenName(companyId, screenName); if (liferayUser == null) { liferayUser = _userLocalService.fetchUserByEmailAddress(companyId, emailAddress); } return liferayUser; } protected long[] getUserOrganizationsIds(String email) { // First get the list of BemisCustomerIds the user is assocaited with long[] userOrganizationIdArray = null; Long organizationId = null; List<Long> userOrganizationIdList = new ArrayList<>(); long companyId = _bemisPortalService.getDefaultCompanyId(); CompanyThreadLocal.setCompanyId(companyId); long organizationClassNameId = _classNameLocalService.getClassNameId(Organization.class.getName()); List<CustomerUserOrgRelation> aCustomerUserOrgRelationList = customerUserOrgRelationLocalService .getCustomerOrgForUserEmail(email); for (CustomerUserOrgRelation aCustomerOrgRelation : aCustomerUserOrgRelationList) { /* For each BemisCustomerId, we need to find the * Organization that matches it */ List<ExpandoValue> expandoValues = _expandoValueLocalService.getColumnValues(companyId, organizationClassNameId, DEFAULT_TABLE_NAME, BEMIS_CUSTOMER_ID, aCustomerOrgRelation.getBemisCustomerId(), -1, -1); for (ExpandoValue expandoValue : expandoValues) { try { organizationId = expandoValue.getClassPK(); Organization org = _organizationLocalService.getOrganization(organizationId); if (_log.isDebugEnabled()) { _log.debug(">>> Found matching organization [" + org.getName() + "]"); } } catch (Exception e) { _log.error(">>> No Such Organization Exist"); } userOrganizationIdList.add(organizationId); if (_log.isDebugEnabled()) { _log.debug(">>> Customer user [" + email + "] should be added to Organization [" + organizationId + "]"); } } } userOrganizationIdArray = userOrganizationIdList.stream().mapToLong(l -> l).toArray(); return userOrganizationIdArray; } protected void migrateCustomerOrgs(Date lastMigrationDate, long setPrototypeId) { // Required items to pass to Organization Service long userId = _bemisPortalService.getDefaultUser().getUserId(); // Iterate through all the parents, create them and their suborgs. List<CustomerOrg> allCustomerOrgParents = customerOrgLocalService.getAllParents(lastMigrationDate); for (CustomerOrg aCustomerOrgParent : allCustomerOrgParents) { // Lets's see what we find. if (_log.isDebugEnabled()) { _log.debug(">>> Read organization [" + aCustomerOrgParent.getCustomerName() + "] from Database"); } /* Save the LR version of the parent org, * Use the default parent class */ Organization aParentOrg = addOrganizationFromCustomer(userId, aCustomerOrgParent, setPrototypeId, OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID); // Get the children for each parent List<CustomerOrg> allMyChildren = customerOrgLocalService .getAllChildren(aCustomerOrgParent.getBemisCustomerId()); /* If the parent has children, then create a parent-like entity * to represent location. There is always one entry returned from * this query representing the parent */ if (allMyChildren.size() > 1) { for (CustomerOrg aCustomerOrgChild : allMyChildren) { if (_log.isDebugEnabled()) { _log.debug(">>> Read organization [" + aCustomerOrgChild.getCustomerName() + "] from Database"); } addOrganizationFromCustomer(userId, aCustomerOrgChild, setPrototypeId, aParentOrg.getOrganizationId()); } } } } protected List<User> migrateCustomerUsers(List<CustomerUser> customerUsers, long companyId) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); List<User> liferayUsers = new ArrayList<>(); for (CustomerUser customerUser : customerUsers) { try { liferayUsers.add(addUser(customerUser, companyId)); } catch (Exception e) { e.printStackTrace(); } } if (_log.isDebugEnabled()) { _log.debug(">>> Customer user migration completed in " + stopWatch.getTime() + "ms: " + liferayUsers.size() + " total users migrated."); } return liferayUsers; } protected void migrateCustomerUsersAsOfDate(Date lastModifiedOnDate, long companyId) { List<CustomerUser> customerUsers = customerUserLocalService.getCustomerUsers(lastModifiedOnDate); migrateCustomerUsers(customerUsers, companyId); } private static final Log _log = LogFactoryUtil.getLog(CustomerMigrationLocalServiceImpl.class); private static final Calendar _calendar = Calendar.getInstance(); @ServiceReference(type = BemisPortalService.class) private BemisPortalService _bemisPortalService; @ServiceReference(type = ClassNameLocalService.class) private ClassNameLocalService _classNameLocalService; @ServiceReference(type = ContactLocalService.class) private ContactLocalService _contactLocalService; @ServiceReference(type = ExpandoColumnLocalService.class) private ExpandoColumnLocalService _expandoColumnLocalService; @ServiceReference(type = ExpandoTableLocalService.class) private ExpandoTableLocalService _expandoTableLocalService; @ServiceReference(type = ExpandoValueLocalService.class) private ExpandoValueLocalService _expandoValueLocalService; @ServiceReference(type = OrganizationLocalService.class) private OrganizationLocalService _organizationLocalService; @ServiceReference(type = UserLocalService.class) private UserLocalService _userLocalService; }