gt: 			if (transaction != null) {
context: /*
   * $Id: CitizenAccountBusinessBean.java,v 1.86.2.2 2005/11/21 01:11:19 palli Exp $
   * Copyright (C) 2002 Idega hf. All Rights Reserved. This software is the
   * proprietary information of Idega hf. Use is subject to license terms.
   */
  package se.idega.idegaweb.commune.account.citizen.business;
  
  import is.idega.block.family.business.FamilyLogic;
  import is.idega.block.pki.business.PKICertificateInfo;
  import is.idega.block.pki.business.PKILoginBusinessBean;
  
  import java.rmi.RemoteException;
  import java.util.Collection;
  import java.util.Date;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Locale;
  import java.util.Vector;
  
  import javax.ejb.CreateException;
  import javax.ejb.FinderException;
  import javax.transaction.SystemException;
  import javax.transaction.UserTransaction;
  
  import se.idega.idegaweb.commune.account.business.AccountApplicationBusinessBean;
  import se.idega.idegaweb.commune.account.business.AccountBusiness;
  import se.idega.idegaweb.commune.account.citizen.data.AdminListOfApplications;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenAccount;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenAccountHome;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantChildren;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantChildrenHome;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantCohabitant;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantCohabitantHome;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantMovingTo;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantMovingToHome;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantPutChildren;
  import se.idega.idegaweb.commune.account.citizen.data.CitizenApplicantPutChildrenHome;
  import se.idega.idegaweb.commune.account.data.AccountApplication;
  import se.idega.idegaweb.commune.business.CommuneUserBusiness;
  import se.idega.idegaweb.commune.message.business.CommuneMessageBusiness;
  import se.idega.util.PIDChecker;
  
  import com.idega.business.IBOLookupException;
  import com.idega.business.IBORuntimeException;
  import com.idega.core.accesscontrol.business.UserHasLoginException;
  import com.idega.core.accesscontrol.data.LoginTable;
  import com.idega.core.contact.data.Phone;
  import com.idega.core.contact.data.PhoneBMPBean;
  import com.idega.core.contact.data.PhoneHome;
  import com.idega.core.location.business.AddressBusiness;
  import com.idega.core.location.data.Address;
  import com.idega.core.location.data.AddressHome;
  import com.idega.core.location.data.AddressType;
  import com.idega.core.location.data.Commune;
  import com.idega.core.location.data.CommuneHome;
  import com.idega.core.location.data.Country;
  import com.idega.core.location.data.CountryHome;
  import com.idega.core.location.data.PostalCode;
  import com.idega.data.IDOAddRelationshipException;
  import com.idega.data.IDOException;
  import com.idega.data.IDOLookup;
  import com.idega.data.IDOLookupException;
  import com.idega.idegaweb.IWUserContext;
  import com.idega.presentation.IWContext;
  import com.idega.user.data.Gender;
  import com.idega.user.data.GenderHome;
  import com.idega.user.data.User;
  import com.idega.user.data.UserHome;
  import com.idega.util.Encrypter;
  import com.idega.util.IWTimestamp;
  import com.idega.util.LocaleUtil;
  import com.idega.util.text.Name;
  
  /**
   * Last modified: $Date: 2005/11/21 01:11:19 $ by $Author: palli $
   *
   * @author <a href="mail:palli@idega.is">Pall Helgason </a>
   * @author <a href="http://www.staffannoteberg.com">Staffan N?teberg </a>
   * @version $Revision: 1.86.2.2 $
   */
  public class CitizenAccountBusinessBean extends AccountApplicationBusinessBean implements CitizenAccountBusiness, AccountBusiness {
  
  	private boolean acceptApplicationOnCreation = true;
  
  	protected CitizenAccountHome getCitizenAccountHome() throws RemoteException {
  		return (CitizenAccountHome) IDOLookup.getHome(CitizenAccount.class);
  	}
  
  
  	/**
  	 * Creates an application for CitizenAccount for a user with a personalId
  	 * that is in the system.
  	 *
  	 * @param user
  	 *          The user that makes the application
  	 * @param ssn
  	 *          The PersonalId of the User to apply for.
  	 * @param email
  	 *          Email of the user
  	 * @param phoneHome
  	 *          the Home phone of the user
  	 * @param phoneWork
  	 *          the Work phone of the user
  	 * @return Integer appliaction id or null if insertion was unsuccessful
  	 * @throws UserHasLoginException
  	 *           If A User already has a login in the system.
  	 */
  
  	@Override
  	public Integer insertApplication(IWContext iwc, User user, String ssn, String email, String phoneHome, String phoneWork) throws UserHasLoginException {
  		return insertApplication(iwc, user, ssn, email, phoneHome, phoneWork, false);
  	}
  
  	@Override
  	public Integer insertApplication(IWContext iwc, User user, String ssn, String email, String phoneHome, String phoneWork, boolean sendEmail) throws UserHasLoginException {
  		CitizenAccount application = null;
  		UserTransaction transaction = null;
  		PKILoginBusinessBean loginBusiness = PKILoginBusinessBean.createNBSLoginBusiness();
  		boolean hasPKILogin = loginBusiness.hasPKILogin(user);
  		PKICertificateInfo info = loginBusiness.getPKILoggedOnInfo(iwc.getSession());
  
  		try {
  			transaction = getSessionContext().getUserTransaction();
  			transaction.begin();
  			application = ((CitizenAccountHome) IDOLookup.getHome(CitizenAccount.class)).create();
  			application.setSsn(ssn);
  			if (user != null) {
  				application.setOwner(user);
  				if (user.getName() != null) {
  					application.setApplicantName(user.getName());
  				}
  			}
  			application.setPhoneHome(phoneHome);
  			if (!"".equals(email)){
  				application.setEmail(email);
  			}
  			if (phoneWork != null)
  				application.setPhoneWork(phoneWork);
  			application.setCaseStatus(getCaseStatusOpen());
  
  			application.store();
  
  			int applicationID = ((Integer) application.getPrimaryKey()).intValue();
  			if (acceptApplicationOnCreation) {
  				if (hasPKILogin) {
  					acceptApplication(applicationID, user, false);
  				}
  				else {
  					acceptApplication(applicationID, user, sendEmail, "");
  				}
  			}
  			transaction.commit();
  		}
  		catch (Exception e) {
  			if (transaction != null) {
  				try {
  					//application = null;
  					transaction.rollback();
  				}
  				catch (SystemException se) {
  					se.printStackTrace();
  				}
  			}
  			if (e instanceof UserHasLoginException) {
  				throw (UserHasLoginException) e;
  			}
  			e.printStackTrace();
  
  			return null;
  		}
  		//logg in if BankID auth. is ok and acceptApplicationOnCreation is true
  		//...
  		if (application != null && acceptApplicationOnCreation) {
  
  			if (hasPKILogin) {
  				try {
  					loginBusiness.logInByPersonalID(iwc, info.getPersonalId());
  				}
  				catch (Exception e1) {
  					e1.printStackTrace();
  				}
  			}
  		}
  
  		return (Integer) (application == null ? null : application.getPrimaryKey());
  	}
  
  	@Override
  	public Integer insertApplication(IWContext iwc, final String name, final String ssn, final String email, final String phoneHome, final String phoneWork, final String careOf
  , final String street, final String zipCode, final String city, final String civilStatus, final boolean hasCohabitant, final int childrenCount, final String applicationReason) {
  		CitizenAccount application = null;
  		try {
  			final CitizenAccountHome citizenAccountHome = (CitizenAccountHome) IDOLookup.getHome(CitizenAccount.class);
  			application = citizenAccountHome.create();
  			application.setApplicantName(name != null ? name : "");
  			application.setSsn(ssn != null ? ssn : "");
  			application.setEmail(email != null ? email : "");
  
  
  			application.setPhoneHome(phoneHome != null ? phoneHome : "");
  			application.setPhoneWork(phoneWork != null ? phoneWork : "");
  			application.setCareOf (careOf == null ? "" : careOf);
  			application.setStreet (street != null ? street : "");
  			application.setZipCode(zipCode != null ? zipCode : "");
  			application.setCity(city != null ? city : "");
  			application.setCivilStatus(civilStatus != null ? civilStatus : "");
  			application.setHasCohabitant(hasCohabitant);
  			application.setChildrenCount(childrenCount);
  			application.setApplicationReason(applicationReason != null ? applicationReason : "");
  			application.setCaseStatus(getCaseStatusOpen());
  			application.store();
  		}
  		catch (Exception e) {
  			e.printStackTrace();
  			return null;
  		}
  
  		return (Integer) (application == null ? null : application.getPrimaryKey());
  	}
  
  	@Override
  	public Integer insertCohabitant(final Integer applicationId, final String firstName, final String lastName, final String ssn, final String civilStatus, final String phoneWork) {
  		CitizenApplicantCohabitant cohabitant = null;
  		try {
  			final CitizenApplicantCohabitantHome citizenApplicantCohabitantHome = (CitizenApplicantCohabitantHome) IDOLookup.getHome(CitizenApplicantCohabitant.class);
  			cohabitant = citizenApplicantCohabitantHome.create();
  			cohabitant.setApplicationId(applicationId.intValue());
  			cohabitant.setFirstName(firstName);
  			cohabitant.setLastName(lastName);
  			cohabitant.setSsn(ssn);
  			cohabitant.setCivilStatus(civilStatus);
  			cohabitant.setPhoneWork(phoneWork);
  			cohabitant.store();
  		}
  		catch (Exception e) {
  			e.printStackTrace();
  			return null;
  		}
  
  		return (Integer) (cohabitant == null ? null : cohabitant.getPrimaryKey());
  	}
  
  	@Override
  	public Integer insertChildren(final Integer applicationId, final String firstName, final String lastName, final String ssn) {
  		CitizenApplicantChildren children = null;
  		try {
  			final CitizenApplicantChildrenHome citizenApplicantChildrenHome = (CitizenApplicantChildrenHome) IDOLookup.getHome(CitizenApplicantChildren.class);
  			children = citizenApplicantChildrenHome.create();
  			children.setApplicationId(applicationId.intValue());
  			children.setFirstName(firstName);
  			children.setLastName(lastName);
  			children.setSsn(ssn);
  			children.store();
  		}
  		catch (Exception e) {
  			e.printStackTrace();
  			return null;
  		}
  
  		return (Integer) (children == null ? null : children.getPrimaryKey());
  	}
  
  	@Override
  	public Integer insertMovingTo(final Integer applicationId, final String address, final String date, final String housingType, final String propertyType, final String landlordName, final String landlordPhone, final String landlordAddress) {
  		CitizenApplicantMovingTo movingTo = null;
  		try {
  			final CitizenApplicantMovingToHome citizenApplicantMovingToHome = (CitizenApplicantMovingToHome) IDOLookup.getHome(CitizenApplicantMovingTo.class);
  			movingTo = citizenApplicantMovingToHome.create();
  			movingTo.setApplicationId(applicationId.intValue());
  			movingTo.setAddress(address);
  			movingTo.setMovingInDate(date);
  			movingTo.setHousingType(housingType);
  			movingTo.setPropertyType(propertyType);
  			movingTo.setLandlord(landlordName, landlordPhone, landlordAddress);
  			movingTo.store();
  		}
  		catch (Exception e) {
  			e.printStackTrace();
  			return null;
  		}
  
  		return (Integer) (movingTo == null ? null : movingTo.getPrimaryKey());
  	}
  
  	@Override
  	public Integer insertPutChildren(final Integer applicationId, final String currentCommuneID) {
  		CitizenApplicantPutChildren putChildren = null;
  		try {
  			final CitizenApplicantPutChildrenHome citizenApplicantPutChildrenHome = (CitizenApplicantPutChildrenHome) IDOLookup.getHome(CitizenApplicantPutChildren.class);
  			putChildren = citizenApplicantPutChildrenHome.create();
  			putChildren.setApplicationId(applicationId.intValue());
  			try {
  				putChildren.setCurrentCommuneID(Integer.parseInt(currentCommuneID));
  			}
  			catch (Exception e) {
  				e.printStackTrace();
  			}
  			//putChildren.setCurrentKommun(currentKommun);
  			putChildren.store();
  		}
  		catch (Exception e) {
  			e.printStackTrace();
  			return null;
  		}
  
  		return (Integer) (putChildren == null ? null : putChildren.getPrimaryKey());
  	}
  
  	@Override
  	public CitizenApplicantPutChildren findCitizenApplicantPutChildren(final int applicationId) throws RemoteException, FinderException {
  		CitizenApplicantPutChildrenHome home = (CitizenApplicantPutChildrenHome) IDOLookup.getHome(CitizenApplicantPutChildren.class);
  		return home.findByApplicationId(applicationId);
  	}
  
  	@Override
  	public Commune findCommuneByCommunePK(Object communePK) throws FinderException, IDOLookupException {
  		CommuneHome comm = (CommuneHome) IDOLookup.getHome(Commune.class);
  		return comm.findByPrimaryKey(communePK);
  	}
  
  	@Override
  	public CitizenApplicantChildren[] findCitizenApplicantChildren(final int applicationId) throws RemoteException, FinderException {
  		CitizenApplicantChildrenHome home = (CitizenApplicantChildrenHome) IDOLookup.getHome(CitizenApplicantChildren.class);
  		return home.findByApplicationId(applicationId);
  	}
  
  	@Override
  	public CitizenApplicantCohabitant findCitizenApplicantCohabitant(final int applicationId) throws RemoteException, FinderException {
  		CitizenApplicantCohabitantHome home = (CitizenApplicantCohabitantHome) IDOLookup.getHome(CitizenApplicantCohabitant.class);
  		return home.findByApplicationId(applicationId);
  	}
  
  	@Override
  	public CitizenApplicantMovingTo findCitizenApplicantMovingTo(final int applicationId) throws RemoteException, FinderException {
  		CitizenApplicantMovingToHome home = (CitizenApplicantMovingToHome) IDOLookup.getHome(CitizenApplicantMovingTo.class);
  		return home.findByApplicationId(applicationId);
  	}
  
  	@Override
  	public User getUser(String ssn) {
  		return getUser(ssn, LocaleUtil.getSwedishLocale());
  	}
  
  	@Override
  	public User getUser(String ssn, Locale locale) {
  		User user = null;
  		try {
  			StringBuffer userSsn = new StringBuffer(ssn);
  			int i = ssn.indexOf('-');
  			if (i != -1) {
  				userSsn.deleteCharAt(i);
  			}
  			if (locale.equals(LocaleUtil.getSwedishLocale())) {
  				if (userSsn.length() == 10) {
  					userSsn.insert(0, "19");
  				}
  			}
  			user = ((UserHome) IDOLookup.getHome(User.class)).findByPersonalID(userSsn.toString());
  		}
  		catch (RemoteException e) {
  			return null;
  		}
  		catch (FinderException e) {
  			if (ssn.length() == 10) {
  				StringBuffer userSsn = new StringBuffer("20");
  				userSsn.append(ssn);
  				try {
  					user = ((UserHome) IDOLookup.getHome(User.class)).findByPersonalID(userSsn.toString());
  				}
  				catch (Exception ex) {
  					return null;
  				}
  			}
  		}
  
  		return user;
  	}
  
  	@Override
  	public User getUserIcelandic(String ssn) {
  		User user = null;
  		try {
  			StringBuffer userSsn = new StringBuffer(ssn);
  			int i = ssn.indexOf('-');
  			if (i != -1) {
  				userSsn.deleteCharAt(i);
  				ssn = userSsn.toString();
  			}
  
  			user = ((UserHome) IDOLookup.getHome(User.class)).findByPersonalID(userSsn.toString());
  		}
  		catch (RemoteException e) {
  			return null;
  		}
  		catch (FinderException e) {
  			if (ssn.length() == 10) {
  				StringBuffer userSsn = new StringBuffer("20");
  				userSsn.append(ssn);
  				try {
  					user = ((UserHome) IDOLookup.getHome(User.class)).findByPersonalID(userSsn.toString());
  				}
  				catch (Exception ex) {
  					return null;
  				}
  			}
  		}
  
  		return user;
  	}
  
  
  
  
  	/**
  	 * Method getListOfUnapprovedApplications.
  	 *
  	 * @return A {@link java.util.List List}of
  	 *         {@link se.idega.idegaweb.commune.citizen.data.AdminListOfApplications AdminListOfApplications}
  	 *         containing information about the unhandled applications in the
  	 *         system.
  	 */
  	@Override
  	public List getListOfUnapprovedApplications() {
  		Vector li = new Vector();
  		try {
  			CitizenAccountHome home = (CitizenAccountHome) IDOLookup.getHome(CitizenAccount.class);
  			Collection cases = home.findAllCasesByStatus(getCaseStatusOpen());
  			Iterator it = cases.iterator();
  			while (it.hasNext()) {
  				CitizenAccount account = (CitizenAccount) it.next();
  				User user = account.getOwner();
  				AdminListOfApplications apps = new AdminListOfApplications();
  				apps.setPID(account.getSsn());
  				apps.setId(((Integer) account.getPrimaryKey()).toString());
  				if (user == null) {
  					// There's no user with this ssn in the system
  					apps.setName(account.getApplicantName());
  					apps.setAddress(account.getStreet() + "; " + account.getZipCode() + " " + account.getCity());
  				}
  				else {
  					// User is allready with this ssn in the system
  					apps.setName(user.getName());
  					Collection addresses = user.getAddresses();
  					Iterator it2 = addresses.iterator();
  					Address address = null;
  					if (it2.hasNext())
  						address = (Address) it2.next();
  					if (address != null && address.getStreetName() != null) {
  						StringBuffer fullAddress = new StringBuffer(address.getStreetName());
  						if (address.getStreetNumber() != null) {
  							fullAddress.append(" ");
  							fullAddress.append(address.getStreetNumber());
  						}
  						apps.setAddress(fullAddress.toString());
  					}
  				}
  
  				li.addElement(apps);
  			}
  		}
  		catch (FinderException e) {
  			return null;
  		}
  		catch (RemoteException e) {
  			return null;
  		}
  
  		return li;
  	}
  
  	@Override
  	protected AccountApplication getApplication(int applicationID) throws FinderException {
  		return getAccount(applicationID);
  	}
  
  	@Override
  	public CitizenAccount getAccount(int id) throws FinderException {
  		try {
  			CitizenAccountHome home = (CitizenAccountHome) IDOLookup.getHome(CitizenAccount.class);
  			return (CitizenAccount) home.findByPrimaryKeyIDO(new Integer(id));
  		}
  		catch (IDOLookupException ile) {
  			throw new IBORuntimeException(ile);
  		}
  	}
  
  	@Override
  	protected Class getCaseEntityClass() {
  		return CitizenAccount.class;
  	}
  
  	@Override
  	public void acceptApplication(final int applicationID, final User performer, boolean createUserMessage, boolean createPasswordMessage, boolean sendEmail) throws CreateException {
  		UserTransaction transaction = null;
  		try {
  			transaction = getSessionContext().getUserTransaction();
  			transaction.begin();
  			final CitizenAccount applicant = getAccount(applicationID);
  			final String name = applicant.getApplicantName();
  			final int spaceIndex = name != null ? name.indexOf(" ") : -1;
  			final String firstName = spaceIndex != -1 ? name.substring(0, spaceIndex) : "";
  			final String lastName = spaceIndex != -1 ? name.substring(spaceIndex + 1, name.length()) : (name != null ? name : "");
  			final String ssn = applicant.getSsn();
  			final GenderHome genderHome = (GenderHome) IDOLookup.getHome(Gender.class);
  			final PIDChecker pidChecker = PIDChecker.getInstance();
  			final Gender gender = pidChecker.isFemale(ssn) ? genderHome.getFemaleGender() : genderHome.getMaleGender();
  			final Date birthDate = pidChecker.getDateFromPersonalID(ssn);
  			final IWTimestamp timestamp = birthDate != null ? new IWTimestamp(birthDate.getTime()) : null;
  			final CommuneUserBusiness userBusiness = getUserBusiness();
  			final String applicationReason = applicant.getApplicationReason();
  			final boolean notNackaResident = applicationReason != null && (applicationReason.equals(CitizenAccount.PUT_CHILDREN_IN_NACKA_SCHOOL_KEY) || applicationReason.equals(CitizenAccount.PUT_CHILDREN_IN_NACKA_CHILDCARE_KEY) || applicationReason.equals(CitizenAccount.MOVING_TO_NACKA_KEY));
  			final User user = notNackaResident ? userBusiness.createSpecialCitizenByPersonalIDIfDoesNotExist(firstName, "", lastName, ssn, gender, timestamp) : userBusiness.createOrUpdateCitizenByPersonalID(firstName, "", lastName, ssn, gender, timestamp);
  			Integer communeId = null;
  			boolean isSweden = true;
  			try {
  				final CitizenApplicantPutChildrenHome putChildrenHome = (CitizenApplicantPutChildrenHome) IDOLookup.getHome(CitizenApplicantPutChildren.class);
  				final CitizenApplicantPutChildren putChildren = putChildrenHome.findByApplicationId(applicationID);
  				communeId = new Integer(putChildren.getCurrentCommuneId());
  			}
  			catch (Exception e) {
  				// no problem, there's no home commune set
  				isSweden = false;
  			}
  			final String streetName = applicant.getStreet();
  			final String careOf = applicant.getCareOf();
  			final String postalCode = applicant.getZipCode();
  			final String postalName = applicant.getCity();
  			final Address address
  					= createAddress(user, communeId, isSweden, streetName, careOf,
  													postalCode, postalName);
  			//createEmail(applicant, user);
  			userBusiness.storeUserEmail(user,applicant.getEmail(),false);
  
  			final Phone homePhone= createPhone(user, PhoneBMPBean.getHomeNumberID(),applicant.getPhoneHome());
  			createPhone (user, PhoneBMPBean.getMobileNumberID(),applicant.getPhoneWork());
  			//userBusiness.updateUserHomePhone(user,applicant.getPhoneHome());
  			//userBusiness.updateUserWorkPhone(user,applicant.getPhoneWork());
  
  			final FamilyLogic familyLogic = (FamilyLogic) getServiceInstance(FamilyLogic.class);
  			User cohabitant = null;
  			if (applicant.hasCohabitant()) {
  				cohabitant = createCohabitant
  						(applicationID, genderHome, pidChecker, userBusiness,
  						 notNackaResident, user, address, homePhone, familyLogic);
  			}
  			if (applicant.getChildrenCount() > 0) {
  				final CitizenApplicantChildrenHome home = (CitizenApplicantChildrenHome)
  						IDOLookup.getHome(CitizenApplicantChildren.class);
  				final CitizenApplicantChildren[] children
  						= home.findByApplicationId(applicationID);
  				for (int i = 0; i < children.length; i++) {
  					final CitizenApplicantChildren child = children [i];
  					createChild (genderHome, pidChecker, userBusiness,
  											 notNackaResident, user,cohabitant, address,	homePhone, familyLogic,
  											 child);
  				}
  			}
  			applicant.setOwner(user);
  			applicant.store();
  			super.acceptApplication(applicationID, performer, createUserMessage,
  															createPasswordMessage, sendEmail);
  			transaction.commit();
  		}
  		catch (Exception e) {
  