Java tutorial
/* * EYWA.COM (Eywa Commerce) * This program is an integrated platform with E-Commerce and Configurator system. * Support: Please, contact the Author on http://www.smartfeeling.org. * Copyright (C) 2014 Gian Angelo Geminiani * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * */ package com.eywa.impl.app.mongo.services; import com.eywa.impl.app.controllers.central.CentralControl; import com.eywa.impl.app.mongo.entities.*; import com.eywa.impl.app.mongo.entities.items.ItemBillingUser; import com.eywa.impl.app.resources.templates.user.UserTemplate; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBObject; import org.ly.Smartly; import org.ly.commons.cryptograph.MD5; import org.ly.commons.util.CollectionUtils; import org.ly.commons.util.LocaleUtils; import org.ly.commons.util.StringUtils; import org.ly.packages.mongo.impl.StandardCodedException; import org.ly.packages.mongo.impl.db.entity.MongoUser; import org.ly.packages.mongo.impl.db.service.MongoCountryService; import org.ly.packages.mongo.impl.db.service.MongoUserService; import org.ly.packages.mongo.impl.util.MongoUtils; import org.ly.proxies.DBProxy; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** * @author angelo.geminiani */ public class UserService extends MongoUserService { // -------------------------------------------------------------------- // c o n s t a n t s // -------------------------------------------------------------------- // -------------------------------------------------------------------- // c o n s t r u c t o r // -------------------------------------------------------------------- public UserService() throws Exception { super((DB) DBProxy.get().getDBMain(), //(DB)DBProxy.get().getDBMain(), Smartly.getLanguages()); } // -------------------------------------------------------------------- // p u b l i c // -------------------------------------------------------------------- public int upsertNative(final DBObject item) throws StandardCodedException { return super.upsert(item); } public int upsert(final DBObject item) throws StandardCodedException { // add main email to emails User.addEmail(item, User.getEmail(item)); // regenerate keys User.regenerateParallelArrayKey(item); return super.upsert(item); } public DBObject signin(final String id_user, final String password) { DBObject user = super.signin(id_user, password); if (null == user) { final DBObject query = new BasicDBObject(); query.put(User.EMAILS, id_user); query.put(User.PASSWORD, password); final List<DBObject> list = super.find(query); if (!list.isEmpty()) { if (list.size() == 1) { user = list.get(0); } else { final String msg = "FOUND MULTIPLE USERS WITH SAME IDENTITY: " + list.toString(); // send email to administrator CentralControl.onError(msg, null); } } } return user; } public DBObject signup(final DBObject hash_user, final boolean auto_enable) throws Exception { // get template and apply to hash_user final String template = UserTemplate.getJson(hash_user.toMap()); final DBObject user = MongoUtils.parseObject(template); if (!hasLang(user)) { User.setLang(user, Smartly.getLang()); } else { User.setLang(user, LocaleUtils.getLanguage(User.getLang(user))); } // email if (StringUtils.hasText(User.getEmail(user))) { User.addEmail(user, User.getEmail(user)); } User.setEnabled(user, auto_enable); User.setFindable(user, true); if (!hasId(user)) { User.setId(user, User.createUUID()); } User.setBilling(user, new ItemBillingUser()); final String password = User.getPassword(user); // encode password User.setPassword(user, MD5.encode(password)); //-- insert new user--// this.insert(user); this.initCountry(user); // reinsert password in clear text User.setPassword(user, password); return user; } public void initCountry(final DBObject user) { if (null != user) { final String countryId = MongoUtils.getString(user, User.COUNTRY_ID); if (StringUtils.hasText(countryId)) { final DBObject country = this.getCountry(countryId); MongoUser.setCountry(user, country); } } } public void putUserUnderDomain(final DBObject user, final DBObject domain) throws Exception { if (null != user && null != domain) { final String domainId = Domain.getId(domain); final String domainOwnerId = Domain.getUserId(domain); final String userId = User.getId(user); final boolean isDomainOwner = userId.equalsIgnoreCase(domainOwnerId); //-- update user --// User.setDomainId(user, domainId); super.upsert(user); //-- update hubs --// final HubService hubSrvc = new HubService(); final List<DBObject> hubs = hubSrvc.getByUserId(userId); for (final DBObject hub : hubs) { // exclude home and recycle bin if (!Hub.isHome(hub) && !Hub.isRecycleBin(hub)) { Hub.setDomainId(hub, domainId); hubSrvc.upsert(hub); //-- updates files, stuff and contacts in this hub --// final String hubId = Hub.getId(hub); //-- FILES --// final FileService srvcFile = new FileService(); final List<DBObject> files = srvcFile.getByHubId(userId, hubId, null); for (final DBObject file : files) { File.setDomainId(file, domainId); srvcFile.upsert(file); } //-- CONTACTS --// final ContactService srvcContact = new ContactService(); final List<DBObject> contacts = srvcContact.getByHubId(userId, hubId, null); for (final DBObject contact : contacts) { Contact.setDomainId(contact, domainId); srvcContact.upsert(contact); } } } //-- update other users with same email domain --// final List<DBObject> siblings = getByDomainUid(Domain.getUid(domain), null); for (final DBObject sibling : siblings) { putUserUnderDomain(sibling, domain); } } } // -------------------------------------------------------------------- // p r i v a t e // -------------------------------------------------------------------- private DBObject getCountry(final String countryId) { final MongoCountryService srvc = new MongoCountryService(super.getDb(), super.getLanguages()); return srvc.findById(countryId); } private static boolean hasId(final DBObject user) { return StringUtils.hasText(User.getId(user)); } private static boolean hasLang(final DBObject user) { return StringUtils.hasText(User.getLang(user)); } // -------------------------------------------------------------------- // S T A T I C // -------------------------------------------------------------------- public static DBObject get(final String userId) { try { final UserService srvc = new UserService(); return srvc.findById(userId); } catch (Throwable ignored) { // something wrong in database } return null; } public static String getLang(final String userId) { try { final UserService srvc = new UserService(); final DBObject query = new BasicDBObject(); query.put(User.ID, userId); final DBObject user = srvc.findOne(query, new String[] { User.LANG }); return User.getLang(user); } catch (Throwable ignored) { // something wrong in database } return LocaleUtils.getCurrent().getLanguage(); } public static boolean existsUser(final DBObject user) throws Exception { final String id = User.getId(user); if (StringUtils.hasText(id) && null != get(id)) { return true; } final String[] emails = User.getEmailsAsArray(user); return emails.length > 0 && null != getOneByEmails(emails, new String[] { User.ID }); } /** * Returns true if user exists and is enabled * * @param userId User ID * @return Boolean */ public static boolean enabled(final String userId) { try { final UserService srvc = new UserService(); return null != srvc.getById(userId, true); } catch (Throwable ignored) { // something wrong in database } return false; } public static DBObject getEnabled(final String userId) { try { final UserService srvc = new UserService(); return srvc.getById(userId, true); } catch (Throwable ignored) { // something wrong in database } return null; } public static DBObject getOneByEmails(final DBObject contact, final String[] fieldNames) { try { final Set<String> emails = new HashSet<String>(Contact.getEmails(contact)); return getOneByEmails(emails.toArray(new String[emails.size()]), fieldNames); } catch (Throwable ignored) { // something wrong in database } return null; } public static DBObject getOneByEmails(final String[] emails, final String[] fieldNames) { try { final UserService srvc = new UserService(); final DBObject query = new BasicDBObject(); MongoUtils.queryIn(query, User.EMAILS, emails); return srvc.findOne(query, fieldNames); } catch (Throwable ignored) { // something wrong in database } return null; } public static List<DBObject> getByEmails(final String[] emails, final String[] fieldNames) { try { final UserService srvc = new UserService(); final DBObject query = new BasicDBObject(); MongoUtils.queryIn(query, User.EMAILS, emails); return srvc.find(query, fieldNames, null, null); } catch (Throwable ignored) { // something wrong in database } return null; } public static List<DBObject> getByKey(final String key) { return getByKeys(new String[] { key }, null); } public static List<DBObject> getByKeys(final String[] keys) { return getByKeys(keys, null); } public static List<DBObject> getByKeys(final String[] keys, final String[] fieldNames) { try { final UserService srvc = new UserService(); final DBObject query = new BasicDBObject(); MongoUtils.queryIn(query, User.PARALLEL_ARRAY_KEY, keys); return srvc.find(query, fieldNames, null, null); } catch (Throwable ignored) { // something wrong in database } return null; } public static List<DBObject> getByDomainUid(final String domainUid, final String[] fieldNames) { try { final UserService srvc = new UserService(); final DBObject query = new BasicDBObject(); final Pattern equal = MongoUtils.patternEndWith("@" + domainUid); query.put(User.EMAIL, equal); return srvc.find(query, fieldNames, null, null); } catch (Throwable ignored) { // something wrong in database } return null; } public static int countByDomainUid(final String domainUid) { try { final UserService srvc = new UserService(); final DBObject query = new BasicDBObject(); final Pattern equal = MongoUtils.patternEndWith("@" + domainUid); query.put(User.EMAIL, equal); return srvc.count(query); } catch (Throwable ignored) { // something wrong in database } return 0; } public static void setDomain(final DBObject user, final DBObject domain) { try { final UserService srvc = new UserService(); srvc.putUserUnderDomain(user, domain); } catch (Throwable ignored) { // something wrong in database } } public static DBObject getShopTemplate(final String userId) { final DBObject user = get(userId); if (null != user) { final DBObject template = ShopTemplateService.get(User.getShopTemplateId(user)); if (null != template) { return template; } } return null; } public static String getAccountType(final String userId) { try { final UserService srvc = new UserService(); final DBObject query = new BasicDBObject(User.ID, userId); final DBObject user = CollectionUtils .getFirst(srvc.find(query, new String[] { User.BILLING }, null, null)); if (null != user) { return ItemBillingUser.getType(User.getBilling(user)); } } catch (Throwable ignored) { } return null; } public static DBObject getStatus(final String userId) { final DBObject user = get(userId); final DBObject result = new BasicDBObject(); if (null != user) { final List<DBObject> accounts = UserExternalAccountService.getAccounts(userId); final DBObject billing = User.getBilling(user); final double div = 4.0; double count = 0; count += StringUtils.hasText(User.getRealname(user)) ? 1 : 0; count += User.getEmails(user).size() > 1 ? User.getEmails(user).size() - 1 : 0; count += StringUtils.hasText(ItemBillingUser.getName(billing)) && StringUtils.hasText(ItemBillingUser.getAddress(billing)) && StringUtils.hasText(ItemBillingUser.getVat(billing)) ? 2 : 0; count += accounts.size() > 0 ? 1 : 0; if (count > div) { count = div; } result.put("active", User.getEnabled(user)); result.put("completeness", (count / div) * 100); } return result; } public static DBObject createChild(final String userId) { try { final UserService srvcUser = new UserService(); final DBObject parent = srvcUser.findById(userId); if (null != parent) { final DBObject newUser = new User(); User.setRootId(newUser, User.getRootId(parent)); User.setParentId(newUser, User.getId(parent)); User.setParentPath(newUser, StringUtils.concatDot(User.getParentPath(parent), User.getId(parent))); User.setLang(newUser, User.getLang(parent)); srvcUser.upsert(newUser); return srvcUser.findById(User.getId(newUser)); } } catch (Throwable ignored) { } return null; } /** * Add/remove collaboration to shop * * @param add Boolean * @param shopId Shop ID * @param userId User ID * @return User */ public static DBObject collaborateToShop(final boolean add, final String shopId, final String userId) { try { if (StringUtils.hasText(shopId) && StringUtils.hasText(userId)) { final ShopService srvcShop = new ShopService(); final UserService srvcUser = new UserService(); final DBObject shop = srvcShop.findById(shopId); final DBObject user = srvcUser.findById(userId); if (null != user && null != shop) { if (add) { // add Shop.addCollaborator(shop, userId); User.addCollaboration(user, shopId); } else { // remove Shop.removeCollaborator(shop, userId); User.removeCollaboration(user, shopId); } srvcShop.upsert(shop); srvcUser.upsert(user); return user; } } } catch (final Throwable ignored) { } // user cannot be added as collaborator return null; } }