no.abmu.user.service.hibernate3.UserImportServiceH3Impl.java Source code

Java tutorial

Introduction

Here is the source code for no.abmu.user.service.hibernate3.UserImportServiceH3Impl.java

Source

/*$Id: UserImportServiceH3Impl.java 13614 2009-04-03 07:17:16Z jens $*/
/*
 ****************************************************************************
 *                                                                          *
 *                   (c) Copyright 2008 ABM-utvikling                       *
 *                                                                          *
 *                                                                          *
 * 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 2 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. http://www.gnu.org/licenses/gpl.html    *
 *                                                                          *
 ****************************************************************************
 */

package no.abmu.user.service.hibernate3;

import java.util.List;

import no.abmu.common.domain.Entity;
import no.abmu.common.persistence.hibernate3.Hibernate3Util;
import no.abmu.organisationregister.util.OrganisationUnitImportExcelParser;
import no.abmu.user.domain.UserRoleNameConst;
import no.abmu.user.service.AbstractUserImportService;
import no.abmu.user.util.UserDataLoaderUtils;
import no.abmu.util.test.Assert;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * <code>UserImportServiceH2Impl</code> implements interface
 * OrganisationUnitImportService. 
 * 
 * @author Jens Vindvad, Jens.Vindvad@abm-utvikling.no
 * @author $Author: jens $
 * @version $Rev: 13614 $
 * $Date: 2009-04-03 09:17:16 +0200 (Fri, 03 Apr 2009) $
 * copyright ABM-Utvikling
 *
 */
public class UserImportServiceH3Impl extends AbstractUserImportService {

    private static final Log logger = (Log) LogFactory.getLog(UserImportServiceH3Impl.class);

    private boolean doRollback = true;

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public boolean importFromExcelFile(String fileName, String sheetName, boolean doRollback) {
        Assert.checkRequiredArgument("fileName", fileName);
        Assert.checkRequiredArgument("sheetName", sheetName);

        OrganisationUnitImportExcelParser excelParser = createExcelParser(fileName, sheetName);

        // Check for match between organisationUnit name in Excel-file and OrganisationRegister
        if (!excelParser.hasOrgUnitNamesInExcelExactMatchWithOneAndOnlyOneOrgUnitInDb()) {
            System.out.println("XXX excelParser.checkForOneAndOnlyOneOrganisationUnitIdDb fails  XXXX");
            String errorMessage = "There exists organisationUnit(s) in Excel file which do not match organisationUnitRegister.";
            logger.error(errorMessage);
            throw new IllegalStateException(errorMessage);
        }

        // Check for already existence of user
        if (!checkThatOrganisationUnitsHasNoUser(excelParser)) {
            String errorMessage = "Some organisationUnit(s) has already user, no import.";
            logger.error(errorMessage);
            return false;
        }

        boolean wentOK = false;
        try {
            Session session = sessionFactory.openSession();
            wentOK = runInTransaction(session, excelParser, doRollback);
        } catch (HibernateException e) {
            logger.error("Feil gikk ikke");
            logger.error(e.toString());
        }

        if (wentOK) {
            logger.info("Import went OK");
        } else {
            logger.warn("There was some errors during import .... ");
        }
        return wentOK;
    }

    private boolean runInTransaction(Session session, OrganisationUnitImportExcelParser excelParser,
            boolean rollback) {

        doRollback = rollback;
        boolean runInTransactionWentOk = false;
        Transaction transaction = session.beginTransaction();
        try {
            runInTransactionWentOk = runInTransaction(session, excelParser);
            if (!runInTransactionWentOk) {
                logger.info("doing rollback");
                transaction.rollback();
            } else if (rollback || doRollback) {
                logger.info("doing rollback");
                transaction.rollback();
            }
        } catch (IllegalArgumentException e) {
            transaction.rollback();
            throw e;
        } catch (IllegalStateException e) {
            transaction.rollback();
            throw e;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            logger.error("doing rollback ", throwable);
            transaction.rollback();
        } finally {
            if (!transaction.wasRolledBack() && (!doRollback)) {
                transaction.commit();
            }
            session.close();
        }

        return runInTransactionWentOk;
    }

    private boolean runInTransaction(Session session, OrganisationUnitImportExcelParser excelParser) {

        boolean importWentOK = true;

        // Setting up new key values before storing values in excelFiles.
        init(session);

        // Check for existence for expected roles in UserRegister.
        if (!checkExistanceOfRolesForOrganisationUnits(excelParser)) {
            String errorMessage = "Trying to use non existent role(s).";
            logger.error(errorMessage);
            throw new IllegalStateException(errorMessage);
        }

        excelParser.load();
        for (; excelParser.hasNext(); excelParser.next()) {
            Long user = excelParser.getUser();
            if (user != null && user.equals(Long.valueOf(1))) {
                String orgUnitName = excelParser.getBokmaalName();
                String abmuId = excelParser.getABMU_ID();
                List<Entity> entitiesStoreList = createUserStoreList(abmuId, orgUnitName);
                if (entitiesStoreList == null || entitiesStoreList.size() == 0) {
                    logger.warn("Can not create user for organisationUnit with name: '" + orgUnitName
                            + "' rollback and no import.");
                    doRollback = true;
                    importWentOK = false;
                } else {
                    // Everything went OK saving new user.
                    Hibernate3Util.saveEntities(session, entitiesStoreList);
                }
            }
        }
        return importWentOK;
    }

    private void init(Session session) {
        // Her we will add new key values e.g. roles.
        UserDataLoaderUtils.findOrCreateRoleByName(getUserService(),
                UserRoleNameConst.ROLE_ARCHIVE_COMPLETE_REGISTRATOR);
        UserDataLoaderUtils.findOrCreateRoleByName(getUserService(),
                UserRoleNameConst.ROLE_ARCHIVE_LIGHT_REGISTRATOR);
    }

}