Example usage for org.hibernate LockMode NONE

List of usage examples for org.hibernate LockMode NONE

Introduction

In this page you can find the example usage for org.hibernate LockMode NONE.

Prototype

LockMode NONE

To view the source code for org.hibernate LockMode NONE.

Click Source Link

Document

No lock required.

Usage

From source file:edu.ku.brc.specify.config.init.SpecifyDBSetupWizard.java

License:Open Source License

/**
 * //from   w  w  w  . j av a 2 s . co m
 */
public void configureDatabase() {
    if (wizardType == WizardType.Institution) {
        setupLoginPrefs();
    }

    if (SpecifyDBSetupWizard.this.listener != null) {
        SpecifyDBSetupWizard.this.listener.hide();
    }

    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        protected boolean isOK = false;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            try {
                String dbName = props.getProperty("dbName");
                String hostName = props.getProperty("hostName");
                DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) props.get("driverObj");

                String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create, hostName,
                        dbName);
                if (connStr == null) {
                    connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
                            dbName);
                }

                String saUserName = props.getProperty("saUserName"); // Master Username
                String saPassword = props.getProperty("saPassword"); // Master Password

                BuildSampleDatabase bsd = new BuildSampleDatabase();

                progressFrame = bsd.createProgressFrame(getResourceString("CREATE_DIV"));
                progressFrame.adjustProgressFrame();
                progressFrame.setProcessPercent(true);
                progressFrame.setOverall(0, 12);
                UIRegistry.pushWindow(progressFrame);

                UIHelper.centerAndShow(progressFrame);

                if (!UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(),
                        dbName, connStr, saUserName, saPassword)) {
                    isOK = false;
                    return null;
                }

                Session session = HibernateUtil.getCurrentSession();
                bsd.setSession(session);

                AppContextMgr ac = AppContextMgr.getInstance();
                Institution institution = ac.getClassObject(Institution.class);
                SpecifyUser user = ac.getClassObject(SpecifyUser.class);
                DisciplineType disciplineType = (DisciplineType) props.get("disciplineType");
                DataType dataType = AppContextMgr.getInstance().getClassObject(DataType.class);

                session.lock(institution, LockMode.NONE);
                session.lock(dataType, LockMode.NONE);

                bsd.setDataType(dataType);

                Division division = bsd.createEmptyDivision(institution, disciplineType, user, props, true,
                        true, true);
                if (division != null) {
                    isOK = division != null;

                    progressFrame.incOverall();

                    if (isOK) {
                        SpecifySchemaUpdateService
                                .addIPadExporterTables(DBConnection.getInstance().getConnection());
                        FixDBAfterLogin.fixUserPermissions(true);
                        saveFormatters();
                    }

                    progressFrame.setVisible(false);
                    progressFrame.dispose();
                } else {
                    isOK = false;
                }

            } catch (Exception ex) {
                //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpecifyDBSetupWizard.class, ex);
                ex.printStackTrace();
            }
            return null;
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            // Create Version Record and copy if there is a connection
            if (DBConnection.getInstance().getConnection() != null) {
                String resAppVersion = UIRegistry.getAppVersion();
                String dbVersion = SchemaUpdateService.getInstance().getDBSchemaVersionFromXML();
                SpVersion.createInitialRecord(DBConnection.getInstance().getConnection(), resAppVersion,
                        dbVersion);

                if (UIRegistry.isMobile()) {
                    DBConnection.setCopiedToMachineDisk(true);
                }
            }

            JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                    getLocalizedMessage("BLD_DONE", getResourceString(isOK ? "BLD_OK" : "BLD_NOTOK")),
                    getResourceString("COMPLETE"), JOptionPane.INFORMATION_MESSAGE);

            if (listener != null) {
                listener.hide();
                listener.finished();
            }
        }
    };
    worker.execute();
}

From source file:edu.ku.brc.specify.conversion.SpecifyDBConverter.java

License:Open Source License

/**
 * Convert old Database to New /* w  w w  .  j a  va2 s.c  o m*/
 * @param databaseNameSource name of an old database
 * @param databaseNameDest name of new DB
 * @throws Exception xx
 */
@SuppressWarnings("unchecked")
protected void convertDB(final String dbNameSource, final String dbNameDest) throws Exception {
    //System.setProperty(DBMSUserMgr.factoryName, "edu.ku.brc.dbsupport.MySQLDMBSUserMgr");

    AppContextMgr.getInstance().clear();

    boolean startfromScratch = true;
    boolean deleteMappingTables = false;

    System.out.println("************************************************************");
    System.out.println("From " + dbNameSource + " to " + dbNameDest);
    System.out.println("************************************************************");

    HibernateUtil.shutdown();

    DatabaseDriverInfo driverInfo = DatabaseDriverInfo.getDriver("MySQL");

    String oldConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            dbNameSource, itUsrPwd.first, itUsrPwd.second, driverInfo.getName());

    String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            dbNameDest, itUsrPwd.first, itUsrPwd.second, driverInfo.getName());

    MySQLDMBSUserMgr mysqlMgr = new MySQLDMBSUserMgr();
    if (mysqlMgr.connectToDBMS(itUsrPwd.first, itUsrPwd.second, hostName)) {
        if (!mysqlMgr.doesDBExists(dbNameDest)) {
            mysqlMgr.createDatabase(dbNameDest);
        }
    }
    mysqlMgr.close();

    // This will log us in and return true/false
    // This will connect without specifying a DB, which allows us to create the DB
    if (!UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbNameDest,
            newConnStr, itUsrPwd.first, itUsrPwd.second)) {
        log.error("Failed connection string: "
                + driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName, dbNameDest,
                        itUsrPwd.first, itUsrPwd.second, driverInfo.getName()));
        throw new RuntimeException(
                "Couldn't login into [" + dbNameDest + "] " + DBConnection.getInstance().getErrorMsg());
    }

    log.debug("Preparing new database");
    frame.setDesc("Gather statistics from " + dbNameDest);
    frame.turnOffOverAll();
    frame.getProcessProgress().setIndeterminate(true);

    UIHelper.centerAndShow(frame);

    DBConnection oldDB = DBConnection.createInstance(driverInfo.getDriverClassName(),
            driverInfo.getDialectClassName(), dbNameDest, oldConnStr, itUsrPwd.first, itUsrPwd.second);

    Connection oldDBConn = oldDB.createConnection();
    Connection newDBConn = DBConnection.getInstance().createConnection();

    if (!isOldDBOK(oldDBConn)) {
        return;
    }

    boolean doUserAgents = false;
    if (doUserAgents) {
        fixupUserAgents(newDBConn);
        return;
    }

    boolean doObs = false;
    if (doObs) {
        ConvertMiscData.convertObservations(oldDBConn, newDBConn, 3);
        return;
    }

    boolean doFixLoanPreps = false;
    if (doFixLoanPreps) {
        // These really aren't working correctly
        fixLoanPreps(oldDBConn, newDBConn);
        fixGiftPreps(oldDBConn, newDBConn);
        return;
    }

    boolean doGetLastEditedByNamesHashSet = false;
    if (doGetLastEditedByNamesHashSet) {
        getOldEditedByStrings(oldDBConn);
        //return;
    }

    boolean doFix = false;
    if (doFix) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        DuplicateCollectingEvents dce = new DuplicateCollectingEvents(oldDBConn, newDBConn);
        //dce.performMaint(true);
        dce.fixCollectorsForCollectingEvents2();
        //dce.removeUnneededCEs();
        return;
    }

    boolean doCEAttrFIx = false;
    if (doCEAttrFIx) {
        frame.setDesc("Fixing Scope....");
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        convLogger.initialize(convOutputPath, dbNameDest);
        TableWriter tblWriter = convLogger.getWriter("ScopeUpdater.html", "Updating Scope Summary");
        ConvScopeFixer convScopeFixer = new ConvScopeFixer(oldDBConn, newDBConn, dbNameDest, tblWriter);
        convScopeFixer.doFixTables();
        oldDBConn.close();
        newDBConn.close();
        System.exit(0);
    }

    boolean doImagesToWebLinks = false;
    if (doImagesToWebLinks) {
        frame.setDesc("Fixing Scope....");
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.convertImagesToWebLinks(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        System.exit(0);
    }

    if (!System.getProperty("user.name").equals("rods")) {
        OldDBStatsDlg dlg = new OldDBStatsDlg(oldDBConn);
        frame.setVisible(false);

        dlg.setVisible(true);
        if (dlg.isCancelled()) {
            oldDBConn.close();
            newDBConn.close();
            System.exit(0);
        }
        doFixCollectors = dlg.doFixAgents();
    }

    startTime = System.currentTimeMillis();

    convLogger.initialize(convOutputPath, dbNameDest);
    convLogger.setIndexTitle(dbNameDest + " Conversion "
            + (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(Calendar.getInstance().getTime()));

    /*if (true)
    {
    TableWriter tDSTblWriter = convLogger.getWriter("TableDataSummary.html", "Table Data Summary", true);
    TableDataChecker tblDataChecker = new TableDataChecker(oldDBConn);
    tblDataChecker.createHTMLReport(tDSTblWriter);
    tDSTblWriter.close();
    return;
    }*/

    boolean doCheckLastEditedByNamesHashSet = false;
    if (doCheckLastEditedByNamesHashSet) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        IdMapperMgr.getInstance().addTableMapper("agent", "AgentID", false);

        convLogger.initialize(convOutputPath, dbNameDest);
        convLogger.setIndexTitle(dbNameDest + " Conversion "
                + (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(Calendar.getInstance().getTime()));
        conversion = new GenericDBConversion(oldDBConn, newDBConn, dbNameSource, convLogger);
        conversion.checkCreatedModifiedByAgents();
        //conversion.fixCreatedModifiedByAgents(itUsrPwd.first, itUsrPwd.second, dbNameSource);
        return;
    }

    boolean doKUINVP = StringUtils.contains(dbNameDest, "kuinvp4_dbo");
    boolean doCUPaleo = StringUtils.contains(dbNameDest, "cupaleo");
    boolean ndgs = StringUtils.contains(dbNameDest, "ndgs");

    if (doCUPaleo) {
        ConvertMiscData.moveHabitatToStratSp5(oldDBConn);
    }

    boolean doFix2 = false;
    if (doFix2) {
        ConvertMiscData.convertMethodFromStratGTP(oldDBConn, newDBConn);
        return;
    }

    frame.setSize(500, frame.getPreferredSize().height);

    frame.setDesc("Fixing NULL Timestamps for conversion.");
    UIHelper.centerAndShow(frame);

    fixOldTablesTimestamps(oldDBConn);

    frame.turnOnOverAll();

    conversion = new GenericDBConversion(oldDBConn, newDBConn, dbNameSource, convLogger);
    GenericDBConversion.CollectionResultType collInitStatus = conversion.initialize();
    if (collInitStatus == GenericDBConversion.CollectionResultType.eError) {
        oldDBConn.close();
        newDBConn.close();
        throw new RuntimeException("There are no collections!");

    } else if (collInitStatus == GenericDBConversion.CollectionResultType.eCancel) {
        oldDBConn.close();
        newDBConn.close();
        System.exit(0);
    }

    boolean doFixDisciplineIntoCEs = false;
    if (doFixDisciplineIntoCEs) {
        doSetDisciplineIntoCEs(oldDBConn, newDBConn);
        return;
    }

    boolean doFixDisciplineIntoLocalities = false;
    if (doFixDisciplineIntoLocalities) {
        doSetDisciplineIntoLocalities(oldDBConn, newDBConn);
        return;
    }

    boolean doFix3 = false;
    if (doFix3) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        AgentConverter agentConverter = new AgentConverter(conversion, IdMapperMgr.getInstance(), false);
        agentConverter.fixMissingAddrsFromConv();
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    boolean doFix4 = false;
    if (doFix4) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.moveStratFieldsToCEA(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    boolean doFix5 = false;
    if (doFix5) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.moveGTPNameToCEText1(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    // For KU Vert Paleo
    boolean doFix6 = false;
    if (doFix6) {
        ConvertTaxonHelper.fixTaxonomicUnitType(oldDBConn);

        oldDBConn.close();
        newDBConn.close();
        return;
    }

    boolean doFix7 = false;
    if (doFix7) {
        IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
        ConvertMiscData.moveGTPNameToLocalityVer(oldDBConn, newDBConn);
        oldDBConn.close();
        newDBConn.close();
        return;
    }

    String sql = "SELECT count(*) FROM (SELECT ce.CollectingEventID, Count(ce.CollectingEventID) as cnt FROM collectingevent AS ce "
            + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
            + "Inner Join collectionobjectcatalog AS cc ON co.CollectionObjectID = cc.CollectionObjectCatalogID "
            + "WHERE ce.BiologicalObjectTypeCollectedID <  21 "
            + "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";

    /*if (true)
    {
    IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
            
    //convLogger.initialize(dbNameDest);
    //convLogger.setIndexTitle(dbNameDest + " Conversion "+(new SimpleDateFormat("yyy-MM-dd hh:mm:ss")).format(Calendar.getInstance().getTime()));
            
    TableWriter tblWriter = convLogger.getWriter("ScopeUpdater.html", "Updating Scope Summary");
    ConvScopeFixer convScopeFixer = new ConvScopeFixer(oldDBConn, newDBConn, dbNameDest, tblWriter);
    convScopeFixer.doFixTables();
    convScopeFixer.checkTables();
    return;
    }*/

    int numCESharing = BasicSQLUtils.getCountAsInt(oldDBConn, sql);

    String msg = String.format(
            "Will this Collection share Collecting Events?\nThere are %d Collecting Events that are sharing now.\n(Sp5 was %ssharing them.)",
            numCESharing, isUsingEmbeddedCEsInSp5() ? "NOT " : "");
    boolean isSharingCollectingEvents = UIHelper.promptForAction("Share", "Adjust CEs",
            "Duplicate Collecting Events", msg);
    boolean doingOneToOneForColObjToCE = !isSharingCollectingEvents;

    conversion.setSharingCollectingEvents(isSharingCollectingEvents);

    /*if (false) 
    {
    createTableSummaryPage();
    return;
    }*/

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            conversion.setFrame(frame);
            frame.setDesc("Building Database Schema...");
            frame.adjustProgressFrame();
            frame.getProcessProgress().setIndeterminate(true);
            frame.getProcessProgress().setString("");
            UIHelper.centerAndShow(frame);

        }
    });

    if (startfromScratch) {
        boolean doBuild = true;
        File file = new File("blank.sql");
        System.err.println(file.getAbsolutePath());
        if (file.exists()) {
            DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
            if (dbMgr.connect(itUsrPwd.first, itUsrPwd.second, "localhost", dbNameDest)) {
                if (dbMgr.doesDBExists(dbNameDest)) {
                    dbMgr.dropDatabase(dbNameDest);
                }

                if (dbMgr.createDatabase(dbNameDest)) {
                    doBuild = false;
                }

                dbMgr.close();
            }

            MySQLBackupService bkService = new MySQLBackupService();

            doBuild = !bkService.doRestore(file.getAbsolutePath(), "/usr/local/mysql/bin/mysql", dbNameDest,
                    itUsrPwd.first, itUsrPwd.second);
        }

        if (doBuild) {
            DBMSUserMgr dbMgr = DBMSUserMgr.getInstance();
            if (dbMgr.connect(itUsrPwd.first, itUsrPwd.second, "localhost", dbNameDest)) {
                if (dbMgr.doesDBExists(dbNameDest)) {
                    dbMgr.dropDatabase(dbNameDest);
                }

                if (dbMgr.createDatabase(dbNameDest)) {
                    doBuild = false;
                }

                dbMgr.close();
            }

            log.debug("Starting from scratch and generating the schema");
            SpecifySchemaGenerator.generateSchema(driverInfo, hostName, dbNameDest, itUsrPwd.first,
                    itUsrPwd.second);
        }
    }

    log.debug("Preparing new database: completed");

    setSession(HibernateUtil.getNewSession());
    IdMapperMgr idMapperMgr = null;
    SpecifyUser specifyUser = null;

    try {
        GenericDBConversion.setShouldCreateMapTables(startfromScratch);
        GenericDBConversion.setShouldDeleteMapTables(deleteMappingTables);

        frame.setOverall(0, OVERALL_STEPS);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UIHelper.centerAndShow(frame);
            }
        });

        boolean doConvert = true;
        if (doConvert) {
            BuildSampleDatabase.createSpecifySAUser(hostName, itUsrPwd.first, itUsrPwd.second,
                    masterUsrPwd.first, masterUsrPwd.second, dbNameDest);

            idMapperMgr = IdMapperMgr.getInstance();
            Connection oldConn = conversion.getOldDBConnection();
            Connection newConn = conversion.getNewDBConnection();
            if (oldConn == null || newConn == null) {
                log.error(
                        "One of the DB connections is null.  Cannot proceed.  Check your DB install to make sure both DBs exist.");
                System.exit(-1);
            }

            idMapperMgr.setDBs(oldConn, newConn);

            // NOTE: Within BasicSQLUtils the connection is for removing tables and records
            BasicSQLUtils.setDBConnection(conversion.getNewDBConnection());

            /*if (false)
            {
            addStorageTreeFomrXML(true);
            return;
            }*/

            //---------------------------------------------------------------------------------------
            //-- Create basic set of information.
            //---------------------------------------------------------------------------------------
            conversion.doInitialize();

            boolean doAll = true;

            if (startfromScratch) {
                BasicSQLUtils.deleteAllRecordsFromTable(conversion.getNewDBConnection(), "agent",
                        BasicSQLUtils.myDestinationServerType);
                BasicSQLUtils.deleteAllRecordsFromTable(conversion.getNewDBConnection(), "address",
                        BasicSQLUtils.myDestinationServerType);
            }
            conversion.initializeAgentInfo(startfromScratch);

            frame.setDesc("Mapping Tables.");
            log.info("Mapping Tables.");
            boolean mapTables = true;
            if (mapTables) {
                // Ignore these field names from new table schema when mapping OR
                // when mapping IDs
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(
                        new String[] { "MethodID", "RoleID", "CollectionID", "ConfidenceID", "TypeStatusNameID",
                                "ObservationMethodID", "StatusID", "TypeID", "ShipmentMethodID", "RankID",
                                "DirectParentRankID", "RequiredParentRankID", "MediumID" });
                conversion.mapIds();
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(null);
            }
            //GenericDBConversion.setShouldCreateMapTables(startfromScratch);

            frame.incOverall();

            Integer institutionId = conversion.createInstitution("Natural History Museum");
            if (institutionId == null) {
                UIRegistry.showError("Problem with creating institution, the Id came back null");
                System.exit(0);
            }

            conversion.convertDivision(institutionId);
            frame.incOverall();

            Agent userAgent = null;
            if (startfromScratch) {
                String username = "testuser";
                String title = "Mr.";
                String firstName = "Test";
                String lastName = "User";
                String midInit = "C";
                String abbrev = "tcu";
                String email = "testuser@ku.edu";
                String userType = SpecifyUserTypes.UserType.Manager.toString();
                String password = "testuser";

                Transaction trans = getSession().beginTransaction();

                //BasicSQLUtils.deleteAllRecordsFromTable(newConn, "usergroup", BasicSQLUtils.myDestinationServerType);
                BasicSQLUtils.deleteAllRecordsFromTable(newConn, "specifyuser",
                        BasicSQLUtils.myDestinationServerType);
                //SpPrincipal userGroup = createUserGroup("admin2");

                Criteria criteria = getSession().createCriteria(Agent.class);
                criteria.add(Restrictions.eq("lastName", lastName));
                criteria.add(Restrictions.eq("firstName", firstName));

                List<?> list = criteria.list();
                if (list != null && list.size() == 1) {
                    userAgent = (Agent) list.get(0);
                } else {
                    userAgent = createAgent(title, firstName, midInit, lastName, abbrev, email);
                }

                Institution institution = (Institution) getSession().createQuery("FROM Institution").list()
                        .get(0);

                String encrypted = Encryption.encrypt(password, password);
                specifyUser = createAdminGroupAndUser(getSession(), institution, null, username, email,
                        encrypted, userType);
                specifyUser.addReference(userAgent, "agents");

                getSession().saveOrUpdate(institution);

                userAgent.setDivision(AppContextMgr.getInstance().getClassObject(Division.class));
                getSession().saveOrUpdate(userAgent);

                trans.commit();
                getSession().flush();

            } else {
                specifyUser = (SpecifyUser) getSession().createCriteria(SpecifyUser.class).list().get(0);
                userAgent = specifyUser.getAgents().iterator().next();

                AppContextMgr.getInstance().setClassObject(SpecifyUser.class, specifyUser);
                // XXX Works for a Single Convert
                Collection collection = (Collection) getSession().createCriteria(Collection.class).list()
                        .get(0);
                AppContextMgr.getInstance().setClassObject(Collection.class, collection);
            }

            /////////////////////////////////////////////////////////////
            // Really need to create or get a proper Discipline Record
            /////////////////////////////////////////////////////////////
            TableWriter taxonTblWriter = convLogger.getWriter("FullTaxon.html", "Taxon Conversion");
            ConvertTaxonHelper taxonHelper = new ConvertTaxonHelper(oldDBConn, newDBConn, dbNameDest, frame,
                    taxonTblWriter, conversion, conversion);
            taxonHelper.createTaxonIdMappings();
            taxonHelper.doForeignKeyMappings();

            frame.setDesc("Converting CollectionObjectDefs.");
            log.info("Converting CollectionObjectDefs.");
            boolean convertDiscipline = doAll;
            if (convertDiscipline) {
                if (!conversion.convertCollectionObjectTypes(specifyUser.getSpecifyUserId())) {
                    return;
                }
            } else {
                idMapperMgr.addTableMapper("CatalogSeriesDefinition", "CatalogSeriesDefinitionID");
                idMapperMgr.addTableMapper("CollectionObjectType", "CollectionObjectTypeID");
            }
            frame.incOverall();

            frame.setDesc("Converting Agents.");
            log.info("Converting Agents.");

            AgentConverter agentConverter = new AgentConverter(conversion, idMapperMgr, startfromScratch);

            // This MUST be done before any of the table copies because it
            // creates the IdMappers for Agent, Address and more importantly AgentAddress
            // NOTE: AgentAddress is actually mapping from the old AgentAddress table to the new Agent table
            boolean copyAgentAddressTables = doAll;
            if (copyAgentAddressTables) {
                log.info("Calling - convertAgents");

                agentConverter.convertAgents(doFixCollectors);

            } else {
                idMapperMgr.addTableMapper("agent", "AgentID");
                idMapperMgr.addTableMapper("agentaddress", "AgentAddressID");
            }
            frame.incOverall();

            frame.setDesc("Mapping Agent Tables.");
            log.info("MappingAgent Tables.");
            if (mapTables) {
                // Ignore these field names from new table schema when mapping OR when mapping IDs
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(
                        new String[] { "MethodID", "RoleID", "CollectionID", "ConfidenceID", "TypeStatusNameID",
                                "ObservationMethodID", "StatusID", "TypeID", "ShipmentMethodID", "RankID",
                                "DirectParentRankID", "RequiredParentRankID", "MediumID" });
                conversion.mapAgentRelatedIds();
                BasicSQLUtils.setFieldsToIgnoreWhenMappingIDs(null);
            }
            frame.incOverall();

            TableWriter gtpTblWriter = convLogger.getWriter("GTP.html", "Geologic Time Period");
            StratToGTP stratToGTP = doCUPaleo || doKUINVP || ndgs
                    ? new StratToGTP(oldDBConn, newDBConn, dbNameDest, gtpTblWriter, conversion)
                    : null;

            frame.setDesc("Converting Geography");
            log.info("Converting Geography");
            boolean doGeography = doAll;
            if (!dbNameDest.startsWith("accessions") && doGeography) {
                GeographyTreeDef treeDef = conversion.createStandardGeographyDefinitionAndItems(true);
                conversion.convertGeography(treeDef, null, true);
            }
            frame.incOverall();

            frame.setDesc("Converting Geologic Time Period.");
            log.info("Converting Geologic Time Period.");
            // GTP needs to be converted here so the stratigraphy conversion can use the IDs
            boolean doGTP = doAll;
            if (doGTP) {
                if (stratToGTP != null) {
                    if (doCUPaleo) {
                        stratToGTP.createGTPTreeDef();
                    } else if (doKUINVP) {
                        stratToGTP.createGTPTreeDefKUINVP();
                    } else if (ndgs) {
                        stratToGTP.createGTPTreeDefNDGS();
                    }
                } else {
                    GeologicTimePeriodTreeDef treeDef = conversion.convertGTPDefAndItems(conversion.isPaleo());
                    conversion.convertGTP(gtpTblWriter, treeDef, conversion.isPaleo());
                }
            } else {
                idMapperMgr.addTableMapper("geologictimeperiod", "GeologicTimePeriodID");
                idMapperMgr.mapForeignKey("Stratigraphy", "GeologicTimePeriodID", "GeologicTimePeriod",
                        "GeologicTimePeriodID");
            }
            frame.incOverall();

            frame.setDesc("Converting Taxonomy");
            log.info("Converting Taxonomy");
            boolean doTaxonomy = doAll;
            if (doTaxonomy) {
                BasicSQLUtils.setTblWriter(taxonTblWriter);
                taxonHelper.doConvert();
                //taxonHelper.convertTaxonCitationToTaxonImage();
                BasicSQLUtils.setTblWriter(null);
            }
            frame.incOverall();

            //-------------------------------------------------------------------------------
            // Get the Discipline Objects and put them into the CollectionInfo Objects
            //-------------------------------------------------------------------------------
            //conversion.loadDisciplineObjects();

            conversion.convertHabitat();

            frame.setDesc("Converting Determinations Records");
            log.info("Converting Determinations Records");
            boolean doDeterminations = doAll;
            if (doDeterminations) {
                frame.incOverall();
                conversion.convertDeterminationRecords();// ZZZ 
            } else {
                frame.incOverall();
            }
            frame.incOverall();

            frame.setDesc("Copying Tables");
            log.info("Copying Tables");
            boolean copyTables = doAll;
            if (copyTables) {
                boolean doBrief = false;
                conversion.copyTables(doBrief);
            }

            frame.incOverall();

            conversion.updateHabitatIds();

            frame.setDesc("Converting Locality");
            log.info("Converting Locality");

            boolean doLocality = doAll;
            if (!dbNameDest.startsWith("accessions") && (doGeography || doLocality)) {
                conversion.convertLocality();
                frame.incOverall();

            } else {
                frame.incOverall();
                frame.incOverall();
            }

            frame.setDesc("Converting DeaccessionCollectionObject");
            log.info("Converting DeaccessionCollectionObject");
            boolean doDeaccessionCollectionObject = doAll;
            if (doDeaccessionCollectionObject) {
                conversion.convertDeaccessionCollectionObject();
            }
            frame.incOverall();

            frame.setDesc("Converting Preparations");
            log.info("Converting Preparations");
            boolean doCollectionObjects = doAll;
            if (doCollectionObjects) {
                if (true) {
                    Session session = HibernateUtil.getCurrentSession();
                    try {
                        // Get a HashMap of all the PrepTypes for each Collection
                        Hashtable<Integer, Map<String, PrepType>> collToPrepTypeHash = new Hashtable<Integer, Map<String, PrepType>>();
                        Query q = session.createQuery("FROM Collection");
                        for (Object dataObj : q.list()) {
                            Collection collection = (Collection) dataObj;
                            Map<String, PrepType> prepTypeMap = conversion
                                    .createPreparationTypesFromUSys(collection); // Hashed by PrepType's Name

                            PrepType miscPT = prepTypeMap.get("misc");
                            if (miscPT != null) {
                                prepTypeMap.put("n/a", miscPT);
                            } else {
                                miscPT = prepTypeMap.get("Misc");
                                if (miscPT != null) {
                                    prepTypeMap.put("n/a", miscPT);
                                } else {
                                    log.error("******************************* Couldn't find 'Misc' PrepType!");
                                }
                            }
                            // So Cache a Map of PrepTYpes for each Collection
                            collToPrepTypeHash.put(collection.getCollectionId(), prepTypeMap);
                        }
                        conversion.convertPreparationRecords(collToPrepTypeHash);// ZZZ 

                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }

                frame.setDesc("Converting Loan Records");
                log.info("Converting Loan Records");
                boolean doLoanPreparations = doAll;
                if (doLoanPreparations) {
                    conversion.convertLoanRecords(false); // Loans
                    conversion.convertLoanAgentRecords(false);// Loans
                    conversion.convertLoanPreparations();

                    frame.setDesc("Converting Gift Records");
                    log.info("Converting Gift Records");
                    conversion.convertLoanAgentRecords(true); // Gifts
                    conversion.convertLoanRecords(true); // Gifts
                    conversion.convertGiftPreparations();
                    frame.incOverall();

                } else {
                    frame.incOverall();
                }

                // Arg1 - Use Numeric Catalog Number
                // Arg2 - Use the Prefix from Catalog Series
                frame.setDesc("Converting CollectionObjects Records");
                log.info("Converting CollectionObjects Records");
                conversion.convertCollectionObjects(true, false);
                frame.incOverall();

            } else {
                frame.incOverall();
                frame.incOverall();
            }

            conversion.updateBioLogicalObjAttrIds();// ZZZ 
            conversion.updatePrepAttrIds();// ZZZ 

            conversion.convertHostTaxonId();

            if (getSession() != null) {
                getSession().close();
                setSession(null);
            }

            setSession(HibernateUtil.getNewSession());

            if (stratToGTP != null) {
                if (doCUPaleo) {
                    stratToGTP.convertStratToGTP();
                } else if (doKUINVP) {
                    stratToGTP.convertStratToGTPKUIVP();

                } else if (ndgs) {
                    stratToGTP.convertStratToGTPNDGS();
                }
            }

            frame.setDesc("Converting Stratigraphy");
            log.info("Converting Stratigraphy");
            boolean doStrat = true;
            if (doStrat) {
                TableWriter tblWriter = convLogger.getWriter("FullStrat.html", "Straigraphy Conversion");
                if (stratToGTP != null) {
                    if (doCUPaleo || ndgs) {
                        stratToGTP.convertStrat(tblWriter, conversion.isPaleo(), doCUPaleo);

                    } else if (doKUINVP) {
                        stratToGTP.convertStratKUINVP(tblWriter, conversion.isPaleo());
                    }
                } else {
                    conversion.convertStrat(tblWriter, conversion.isPaleo());
                }
            }

            //-------------------------------------------
            // Get Discipline and Collection
            //-------------------------------------------

            frame.incOverall();

            if (getSession() != null) {
                getSession().close();
                setSession(null);
            }

            boolean status = false;
            Institution institution = null;
            Division division = null;
            Collection collection = null;
            Discipline dscp = null;
            Session localSession = HibernateUtil.getNewSession();
            Session cachedCurrentSession = getSession();
            setSession(null);
            try {
                if (conversion.getCurDisciplineID() == null) {
                    List<?> list = localSession.createQuery("FROM Discipline").list();
                    dscp = (Discipline) list.get(0);

                } else {
                    log.debug("Loading Discipline with Id[" + conversion.getCurDisciplineID() + "]");
                    List<?> list = localSession
                            .createQuery("FROM Discipline WHERE id = " + conversion.getCurDisciplineID())
                            .list();
                    dscp = (Discipline) list.get(0);
                }
                AppContextMgr.getInstance().setClassObject(Discipline.class, dscp);

                if (dscp.getCollections().size() == 1) {
                    collection = dscp.getCollections().iterator().next();
                }

                if (collection == null) {
                    if (conversion.getCurCollectionID() == null || conversion.getCurCollectionID() == 0) {
                        List<?> list = localSession.createQuery("FROM Collection").list();
                        collection = (Collection) list.get(0);

                    } else {
                        String hsql = "FROM Collection WHERE id = " + conversion.getCurCollectionID();
                        log.info(hsql);
                        List<?> list = localSession.createQuery(hsql).list();
                        if (list == null || list.size() == 0) {
                            UIRegistry.showError("Couldn't find the Collection record [" + hsql + "]");
                        }
                        collection = (Collection) list.get(0);
                    }
                }

                division = dscp.getDivision();
                localSession.lock(division, LockMode.NONE);
                institution = division.getInstitution();
                localSession.lock(institution, LockMode.NONE);
                institution.getDivisions().size();

                AppContextMgr.getInstance().setClassObject(Collection.class, collection);
                AppContextMgr.getInstance().setClassObject(Division.class, division);
                AppContextMgr.getInstance().setClassObject(Institution.class, institution);

                if (doFixCollectors) {
                    agentConverter.fixupForCollectors(division, dscp);
                }

                setSession(localSession);

                try {
                    for (CollectionInfo collInfo : CollectionInfo.getCollectionInfoList(oldDBConn, true)) {
                        if (collInfo.getCollectionId() == null) {
                            log.error("CollectionID: was null for " + collInfo.getCatSeriesName());
                            continue;
                        }
                        List<?> list = localSession
                                .createQuery("FROM Collection WHERE id = " + collInfo.getCollectionId()).list();

                        List<Collection> tmpCollList = (List<Collection>) list;
                        Collection tmpCollection = tmpCollList.get(0);

                        // create the standard user groups for this collection
                        Map<String, SpPrincipal> groupMap = createStandardGroups(localSession, tmpCollection);

                        // add the administrator as a Collections Manager in this group
                        specifyUser.addUserToSpPrincipalGroup(
                                groupMap.get(SpecifyUserTypes.UserType.Manager.toString()));

                        Transaction trans = localSession.beginTransaction();

                        for (SpPrincipal prin : groupMap.values()) {
                            localSession.saveOrUpdate(prin);
                        }

                        localSession.saveOrUpdate(specifyUser);

                        trans.commit();

                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                status = true;

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            localSession.close();

            localSession = HibernateUtil.getNewSession();
            setSession(localSession);

            specifyUser = (SpecifyUser) localSession.merge(specifyUser);

            division = (Division) localSession.createQuery("FROM Division WHERE id = " + division.getId())
                    .list().iterator().next();
            institution = (Institution) localSession
                    .createQuery("FROM Institution WHERE id = " + institution.getId()).list().iterator().next();
            collection = (Collection) localSession
                    .createQuery("FROM Collection WHERE id = " + collection.getId()).list().iterator().next();

            AppContextMgr.getInstance().setClassObject(Collection.class, collection);
            AppContextMgr.getInstance().setClassObject(Division.class, division);
            AppContextMgr.getInstance().setClassObject(Institution.class, institution);

            dscp = (Discipline) localSession.createQuery("FROM Discipline WHERE id = " + dscp.getId()).list()
                    .iterator().next();
            AppContextMgr.getInstance().setClassObject(Discipline.class, dscp);

            localSession.flush();

            setSession(cachedCurrentSession);

            frame.setDesc("Converting USYS Tables.");
            log.info("Converting USYS Tables.");
            boolean copyUSYSTables = doAll;
            if (copyUSYSTables) {
                if (status) {
                    BasicSQLUtils.deleteAllRecordsFromTable("picklist", BasicSQLUtils.myDestinationServerType);
                    BasicSQLUtils.deleteAllRecordsFromTable("picklistitem",
                            BasicSQLUtils.myDestinationServerType);

                    for (Collection collectionObj : (List<Collection>) localSession
                            .createQuery("FROM Collection").list()) {
                        log.debug("Loading PickLists for Collection [" + collectionObj.getCollectionName()
                                + "] id[" + collectionObj.getId() + "]");

                        conversion.convertUSYSTables(localSession, collectionObj);

                        frame.setDesc("Creating PickLists from XML.");

                        BuildSampleDatabase.createPickLists(localSession, null, true, collectionObj);

                        BuildSampleDatabase.createPickLists(localSession, collection.getDiscipline(), true,
                                collectionObj);
                    }

                } else {
                    log.error("STATUS was FALSE for PickList creation!");
                }

                frame.incOverall();

            } else {
                frame.incOverall();
            }

            if (localSession != null) {
                localSession.close();
            }

            frame.incOverall();

            doSetDisciplineIntoCEs(oldDBConn, newDBConn);

            frame.setDesc("Fixing Preferred Taxon");

            // MySQL Only ???
            sql = "UPDATE determination SET PreferredTaxonID = CASE WHEN "
                    + "(SELECT AcceptedID FROM taxon WHERE taxon.TaxonID = determination.TaxonID) IS NULL "
                    + "THEN determination.TaxonID ELSE (SELECT AcceptedID FROM taxon WHERE taxon.TaxonID = determination.TaxonID) END";
            System.out.println(sql);
            BasicSQLUtils.setSkipTrackExceptions(true);
            BasicSQLUtils.update(sql);

            frame.incOverall();

            ShipmentConverter shipmentConv = new ShipmentConverter(oldDBConn, newDBConn);
            shipmentConv.fixup();

            //------------------------------------------------
            // Localize Schema and make form fields visible
            //------------------------------------------------
            frame.setDesc("Localizing the Schema");
            conversion.doLocalizeSchema();

            frame.incOverall();

            //HabitatTaxonIdConverter habitatConverter = new HabitatTaxonIdConverter(oldDB.getConnection(), newDBConn);
            //habitatConverter.convert(conversion.getCollectionMemberId());

            frame.incOverall();

            agentConverter.fixAddressOfRecord();

            frame.incOverall();

            if (dbNameSource.startsWith("gcf")) {
                GulfInvertsFixer giFixer = new GulfInvertsFixer(oldDBConn, newDBConn, dbNameSource, null);
                giFixer.convert(conversion.getCollectionMemberId());
            }
            //checkDisciplines();

            frame.setDesc("Fixing Scope....");
            TableWriter tblWriter = convLogger.getWriter("ScopeUpdater.html", "Updating Scope Summary");
            ConvScopeFixer convScopeFixer = new ConvScopeFixer(oldDBConn, newDBConn, dbNameDest, tblWriter);
            convScopeFixer.doFixTables();
            convScopeFixer.checkTables();

            FixDBAfterLogin.fixUserPermissions(true);

            waitTime = 0;

            /*
            long stTime = System.currentTimeMillis();
                    
            sql = "SELECT count(*) FROM (SELECT ce.CollectingEventID, Count(ce.CollectingEventID) as cnt FROM collectingevent AS ce " +
                "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID " +
                "Inner Join collectionobjectcatalog AS cc ON co.CollectionObjectID = cc.CollectionObjectCatalogID " +    
                "WHERE ce.BiologicalObjectTypeCollectedID <  21 " +
                "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";
                    
            int numCESharing = BasicSQLUtils.getCountAsInt(oldDBConn, sql);
                    
            String msg = String.format("Will this Collection share Collecting Events?\nThere are %d Collecting Events that are sharing now.\n(Sp5 was %ssharing them.)", numCESharing, isUsingEmbeddedCEsInSp5() ? "NOT " : "");
            boolean doingOneToOneForColObjToCE = !UIHelper.promptForAction("Share", "Adjust CEs", "Duplicate Collecting Events", msg);
                    
            waitTime = System.currentTimeMillis() - stTime;
            */

            frame.setDesc("Duplicating CollectingEvents Performing Maintenance...");
            File ceFile = new File(dbNameDest + ".ce_all");
            if (doingOneToOneForColObjToCE) {
                DuplicateCollectingEvents dce = new DuplicateCollectingEvents(oldDBConn, newDBConn, frame,
                        conversion.getCurAgentCreatorID(), dscp.getId());
                dce.performMaint(true);

                FileUtils.writeStringToFile(ceFile, dbNameDest);

            } else if (ceFile.exists()) {
                ceFile.delete();
            }

            //endTime = System.currentTimeMillis();

            int convertTimeInSeconds = (int) ((endTime - startTime - waitTime) / 1000.0);

            int colObjCnt = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectionobject");
            ConvertStatSender sender = new ConvertStatSender();
            sender.sendConvertInfo(dbNameDest, colObjCnt, convertTimeInSeconds);

            frame.incOverall();

            fixHibernateHiLo(newDBConn);

            try {
                frame.setDesc("Discipline Duplicator...");
                DisciplineDuplicator d = new DisciplineDuplicator(conversion.getOldDBConn(),
                        conversion.getNewDBConn(), tblWriter, frame, conversion);
                d.doShowFieldsForDiscipline();
                frame.setDesc("Duplicating Collecting Events...");
                d.duplicateCollectingEvents();
                frame.setDesc("Duplicating Localities...");
                d.duplicateLocalities();
                frame.setDesc("Duplicating Geography...");
                d.duplicateGeography();

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            frame.setDesc("Running Table Checker to report on fields with data.");
            TableWriter tDSTblWriter = convLogger.getWriter("TableDataSummary.html", "Table Data Summary",
                    true);
            TableDataChecker tblDataChecker = new TableDataChecker(oldDBConn);
            tblDataChecker.createHTMLReport(tDSTblWriter);
            //tDSTblWriter.close();

            frame.setDesc("Updating Version...");
            updateVersionInfo(newConn);

            if (dbNameDest.startsWith("kui_fish_") || dbNameDest.startsWith("kui_tissue")) {
                ConvertMiscData.convertKUFishCruiseData(oldDBConn, newDBConn, conversion.getCurDisciplineID());
                ConvertMiscData.convertKUFishObsData(oldDBConn, newDBConn);

            } else if (dbNameDest.startsWith("ku_invert_")) {
                ConvertMiscData.convertKUInvertsObsData(oldDBConn, newDBConn);
            }

            // Check for mismatched Disciplines for CE and CE Attrs
            sql = "SELECT Count(ce.CollectingEventID) FROM collectingevent AS ce "
                    + "Inner Join collectingeventattribute AS cea ON ce.CollectingEventAttributeID = cea.CollectingEventAttributeID "
                    + "WHERE ce.DisciplineID <> cea.DisciplineID";

            int ceCnt = BasicSQLUtils.getCountAsInt(sql);
            if (ceCnt > 0) {
                UIRegistry.showErrorNonModal(String.format(
                        "There are %d CollectingEvents and CE Attributes where their DisciplineID do not match.",
                        ceCnt));
            }

            // Check for ColObjs that have bad DisciplineIDs compared to the Collection's Discipline
            sql = "SELECT Count(ce.CollectingEventID) FROM collectingevent AS ce "
                    + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
                    + "Inner Join collection ON co.CollectionID = collection.UserGroupScopeId "
                    + "WHERE ce.DisciplineID <>  collection.DisciplineID";
            int dspCnt = BasicSQLUtils.getCountAsInt(sql);
            if (dspCnt > 0) {
                UIRegistry.showErrorNonModal(String.format(
                        "There are %d mismatches between the Collection Object Discipline and the Discipline of the Colleciton it is in",
                        dspCnt));
            }

            // Check for One-To-One for ColObj -> CE
            if (doingOneToOneForColObjToCE) {
                sql = "SELECT COUNT(*) FROM (SELECT ce.CollectingEventID, Count(ce.CollectingEventID) AS cnt FROM collectingevent AS ce "
                        + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
                        + "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";
                ceCnt = BasicSQLUtils.getCountAsInt(sql);
                if (ceCnt > 0) {
                    sql = "SELECT id,cnt FROM (SELECT ce.CollectingEventID as id, Count(ce.CollectingEventID) AS cnt FROM collectingevent AS ce "
                            + "Inner Join collectionobject AS co ON ce.CollectingEventID = co.CollectingEventID "
                            + "GROUP BY ce.CollectingEventID) T1 WHERE cnt > 1";
                    for (Object[] row : BasicSQLUtils.query(sql)) {
                        log.debug(String.format("CE[%s] has %s Collection Objects.", row[0].toString(),
                                row[1].toString()));
                    }
                    UIRegistry.showErrorNonModal(String.format(
                            "There are %d CollectingEvents that have more than one Collection Object and they are suppose to be a One-To-One",
                            ceCnt));
                }
            }

            boolean doCheckLastEditedByNamesHashSet2 = !doCheckLastEditedByNamesHashSet;
            if (doCheckLastEditedByNamesHashSet2) {
                conversion.checkCreatedModifiedByAgents();
                //conversion.fixCreatedModifiedByAgents(itUsrPwd.first, itUsrPwd.second, dbNameSource);
            }

            log.info("Done - " + dbNameDest + " " + convertTimeInSeconds);
            frame.setDesc("Done - " + dbNameDest + " " + convertTimeInSeconds);

            //System.setProperty(AppPreferences.factoryName, "edu.ku.brc.specify.config.AppPrefsDBIOIImpl");    // Needed by AppReferences
            System.setProperty("edu.ku.brc.dbsupport.DataProvider",
                    "edu.ku.brc.specify.dbsupport.HibernateDataProvider"); // Needed By the Form System and any Data Get/Set

            createTableSummaryPage();
            conversion.cleanUp();
        }

        if (idMapperMgr != null && GenericDBConversion.shouldDeleteMapTables()) {
            idMapperMgr.cleanup();
        }

        //This will convert Specify5 queries exported from the 5 database to a file that can be imported
        //into the six database. Need to have standard location for files. Can probably also import the queries here.
        //QueryConverter.convert("/home/timo/Desktop/KUI_FishQueries.xml", "/home/timo/convertedSpQ.xml", "/home/timo/UnconvertedFields.xml");

        fixPreparationCollectionMemberID(newDBConn);

        frame.setTitle("Done - " + dbNameDest);
        frame.incOverall();
        frame.processDone();

    } catch (Exception ex) {
        ex.printStackTrace();

        if (idMapperMgr != null && GenericDBConversion.shouldDeleteMapTables()) {
            idMapperMgr.cleanup();
        }

    } finally {
        if (getSession() != null) {
            getSession().close();
        }
    }
}

From source file:edu.ku.brc.specify.dbsupport.HibernateDataProviderSession.java

License:Open Source License

public void attach(final Object dataObj) {
    if (session != null) {
        session.lock(dataObj, LockMode.NONE);

    } else {/*from   w  w w  .j av a2s .co m*/
        log.error("Session was null.", new NullPointerException("Session was null"));
    }
}

From source file:edu.ku.brc.specify.treeutils.HibernateTreeDataServiceImpl.java

License:Open Source License

/**
 * Creates a new Hibernate session and associates the given objects with it.
 * //from  www. ja  v a2s.c  om
 * @param objects the objects to associate with the new session
 * @return the newly created session
 */
private Session getNewSession(final Object... objects) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    for (Object o : objects) {
        if (o != null) {
            // make sure not to attempt locking an unsaved object
            DataModelObjBase dmob = (DataModelObjBase) o;
            if (dmob.getId() != null) {
                session.lock(o, LockMode.NONE);
            }
        }
    }
    return session;
}

From source file:es.urjc.mctwp.dao.GenericDAO.java

License:Open Source License

/**
 * Reattach a detached objetc to persistent context.
 * //www  .  j a  v a2 s.  co m
 * @param dirtyMode, allows to choose between consider an object dirty or clean
 * @param obj
 */
public void reattach(T obj, int dirtyMode) {

    //Avoid bad parameters
    if ((obj != null)) {
        try {
            switch (dirtyMode) {

            case DIRTY_EVALUATION:
                this.getHibernateTemplate().update(obj);
                break;

            case DIRTY_IGNORE:
                this.getHibernateTemplate().lock(obj, LockMode.NONE);
                break;
            }
        } catch (RuntimeException re) {
            logErrMsg("reattach", re);
            throw re;
        }
    }
}

From source file:gov.nih.nci.cabig.caaers.dao.AdverseEventReportingPeriodDao.java

License:BSD License

/**
 * Will reassociate an AdverseEventReportingPeriod object to the running Hibernate Session. 
 * @param o - an AdverseEventReportingPeriod
 *//*from   w w w.j  a v  a2 s  . co  m*/
@Override
public void reassociate(AdverseEventReportingPeriod o) {
    getHibernateTemplate().lock(o, LockMode.NONE);
}

From source file:gov.nih.nci.cabig.caaers.dao.CaaersDao.java

License:BSD License

/**
 * This will lock the object
 * @param o
 */
@Transactional(readOnly = false)
public void lock(T o) {
    getHibernateTemplate().lock(o, LockMode.NONE);
}

From source file:gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao.java

License:BSD License

/**
 * This method will reassociate the domain object to hibernate session. With a lock mode none.
 * /*from   w  w  w .  j  a va2s  . co  m*/
 * @param report -
 *                the domain object instance that is to be reassociated.
 */
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public void reassociate(final ExpeditedAdverseEventReport report) {
    log.debug("Reassociating ExpeditedAdverseEventReport...");
    super.reassociate(report);

    if (report.getReporter() == null || report.getReporter().isTransient()) {
        log.debug("Reporter unsaved; skipping reassociate cascade");
    } else {
        getHibernateTemplate().lock(report.getReporter(), LockMode.NONE);
    }
    if (report.getPhysician() == null || report.getPhysician().isTransient()) {
        log.debug("Physican unsaved; skipping reassociate cascade");
    } else {
        getHibernateTemplate().lock(report.getPhysician(), LockMode.NONE);
    }
}

From source file:gov.nih.nci.cabig.caaers.dao.OrganizationDao.java

License:BSD License

public void lock(Organization org) {
    getHibernateTemplate().lock(org, LockMode.NONE);
}

From source file:gov.nih.nci.cabig.caaers.dao.ParticipantDao.java

License:BSD License

/**
 * This method will reassociate the domain object to hibernate session. With a lock mode none.
 *
 * @param o -//w ww .j a v  a  2s . c om
 *          the domain object instance that is to be reassociated.
 */
public void reassociateUsingLock(Participant o) {
    getHibernateTemplate().lock(o, LockMode.NONE);
}