Example usage for org.apache.commons.lang StringUtils contains

List of usage examples for org.apache.commons.lang StringUtils contains

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils contains.

Prototype

public static boolean contains(String str, String searchStr) 

Source Link

Document

Checks if String contains a search String, handling null.

Usage

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

/**
 * Convert old Database to New /*from   w ww .  j a  va2 s . com*/
 * @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.af.ui.db.DatabaseLoginPanel.java

/**
 * Enables or disables the UI based of the values of the controls. The Login button doesn't
 * become enabled unless everything is filled in. It also expands the "Extra" options if any of
 * them are missing a value/*w ww  .  j  a v  a  2 s  .  co  m*/
 */
protected void updateUIControls() {
    if (extraPanel == null || isLoggingIn) {
        return;
    }

    String dbName = StringUtils.deleteWhitespace(databases.getTextField().getText());
    String uName = username.getText();
    String pwd = new String(password.getPassword());

    boolean shouldEnable = StringUtils.isNotEmpty(uName) && StringUtils.isNotEmpty(pwd)
            && (servers.getComboBox().getSelectedIndex() != -1
                    || StringUtils.isNotEmpty(servers.getTextField().getText()))
            && StringUtils.isNotEmpty(dbName);

    if (shouldEnable && (StringUtils.contains(uName, ' ') || StringUtils.contains(uName, ','))) {
        shouldEnable = false;
        setMessage(getResourceString("NO_SPC_USRNAME"), true); //$NON-NLS-1$

    } else if (shouldEnable && (StringUtils.contains(pwd, ' ') || StringUtils.contains(pwd, ','))) {
        shouldEnable = false;
        setMessage(getResourceString("NO_SPC_PWDNAME"), true); //$NON-NLS-1$

    } else if (shouldEnable && (StringUtils.contains(dbName, ' ') || StringUtils.contains(dbName, ','))) {
        shouldEnable = false;
        setMessage(getResourceString("NO_SPC_DBNAME"), true); //$NON-NLS-1$

    } else if (dbDriverCBX.getSelectedIndex() == -1) {
        shouldEnable = false;
        setMessage(getResourceString("MISSING_DRIVER"), true); //$NON-NLS-1$
        if (!extraPanel.isVisible()) {
            moreBtn.doClick();
        }
    }

    loginBtn.setEnabled(shouldEnable);

    if (shouldEnable) {
        setMessage("", false); //$NON-NLS-1$
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * //from ww w  .jav a2 s  . c om
 */
@SuppressWarnings("unchecked")
public void doSearchOccur(final String occurrenceId) {
    updateMyDataUIState(false);

    points.clear();

    final SimpleGlassPane glassPane = writeSimpleGlassPaneMsg(getLocalizedMessage("LifeMapperTask.PROCESSING"),
            GLASS_FONT_SIZE);
    glassPane.setTextYPos((int) ((double) getSize().height * 0.25));

    // check the website for the info about the latest version
    final HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$
    httpClient.getParams().setParameter("http.socket.timeout", 15000);

    if (list.getSelectedIndex() < 0) {
        return;
    }

    UsageTracker.incrUsageCount("LM.OccurSearch");

    final String lmURL = String.format(
            "http://www.lifemapper.org/services/sdm/occurrences/%s/json?format=specify&fillPoints=true",
            occurrenceId);
    //System.out.println(lmURL);

    SwingWorker<String, String> worker = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            GetMethod getMethod = new GetMethod(lmURL);
            try {
                httpClient.executeMethod(getMethod);

                // get the server response
                //String responseString = getMethod.getResponseBodyAsString();
                byte[] bytes = getMethod.getResponseBody();
                if (bytes != null && bytes.length > 0) {
                    return new String(bytes, "UTF-8");
                }
                //if (StringUtils.isNotEmpty(responseString))
                //{
                //    System.err.println(responseString);
                //}
                return null;
            } catch (java.net.UnknownHostException uex) {
                //log.error(uex.getMessage());
            } catch (java.net.SocketTimeoutException ex) {
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            } catch (Exception e) {
                e.printStackTrace();
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            }

            return null;
        }

        @Override
        protected void done() {
            super.done();

            boolean isError = true;
            boolean parseError = false;

            try {
                String responseString = get();

                if (StringUtils.isNotEmpty(responseString)
                        && StringUtils.contains(responseString.toLowerCase(), "{")) {
                    // Need to change this to using regex to strip away unwanted chars
                    StringBuilder sb = new StringBuilder();
                    String[] lines = StringUtils.split(responseString, '\n');
                    for (String str : lines) {
                        if (str.indexOf("resname") == -1) {
                            sb.append(str);
                        }
                    }
                    String cleaned = sb.toString();

                    parseError = false;
                    try {
                        JSONTokener tok = new JSONTokener(cleaned);
                        if (tok != null) {
                            while (tok.more()) {
                                JSONObject obj = (JSONObject) tok.nextValue();
                                if (obj != null) {
                                    JSONArray pointArray = (JSONArray) obj.get("feature");
                                    if (pointArray != null) {
                                        Iterator<Object> iter = (Iterator<Object>) pointArray.iterator();
                                        while (iter.hasNext()) {
                                            JSONObject pObj = (JSONObject) iter.next();
                                            if (pObj != null) {
                                                String lat = null;//(String)pObj.get("lat");
                                                String lon = null;//(String)pObj.get("lon");
                                                String geomwkt = (String) pObj.get("geomwkt");
                                                if (geomwkt != null) {
                                                    //quel cheapo...
                                                    geomwkt = geomwkt.replace("POINT", "");
                                                    geomwkt = geomwkt.replace("(", "");
                                                    geomwkt = geomwkt.replace(")", "");
                                                    geomwkt = geomwkt.trim();
                                                    String[] geocs = geomwkt.split(" ");
                                                    if (geocs.length == 2) {
                                                        lon = geocs[0];
                                                        lat = geocs[1];
                                                    }
                                                }
                                                //System.out.println(lat+"  "+lon);
                                                if (lat != null && lon != null) {
                                                    LatLonPlacemark plcMark = new LatLonPlacemark(markerImg,
                                                            Double.parseDouble(lat.trim()),
                                                            Double.parseDouble(lon.trim()));
                                                    points.add(plcMark);
                                                }
                                            }
                                        }
                                        isError = false;
                                    }
                                }
                            }
                        }
                    } catch (net.sf.json.JSONException ex) {
                        System.err.println(ex.getLocalizedMessage());
                        parseError = true;
                    }

                    boolean hasPnts = points.size() > 0;
                    updateMyDataUIState(hasPnts && StringUtils.isNotEmpty(myDataTF.getText()));
                    if (hasPnts) {
                        imgDisplay.setImage((Image) null);
                        wwPanel.placeMarkers(points, false, true, 0, null, false);

                        imgRequestCnt = 0;

                        imgURL = makeURL(occurSet);

                        getImageFromWeb(imgURL, pointsMapImageListener);

                    } else {
                        isError = false;
                    }

                } else {
                    UsageTracker.incrUsageCount("LM.OccurSearchErr");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            if (isError || parseError) {
                showErrorMsg(glassPane, "LifeMapperTask.PROC_ERR");
            } else {
                clearSimpleGlassPaneMsg();
            }
        }
    };
    worker.execute();
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.AgentCleanupProcessor.java

/**
 * @param message/*from   w  w  w.ja  va2s  .c  o  m*/
 */
private void showProcessingMessage(final String message) {
    String msg = message;
    if (StringUtils.contains(msg.toLowerCase(), "<br>")) {
        msg = StringUtils.replace(msg, "<BR>", "\n");
    }
    cleanupIndexer.getPrgDlg().toBack();
    UIRegistry.displayInfoMsgDlg(msg);
    cleanupIndexer.getPrgDlg().toFront();
}

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

/**
 * @param si// w  ww  . j a  va2s  .  c  o m
 * @param level
 * @param id
 * @param stmt
 * @throws SQLException
 */
protected void deleteRecords(final StackItem si, final int level, final int id, final Statement stmt,
        final boolean doDeletes) throws SQLException {

    if (!doTrees && (si.getTableInfo() == null
            || Treeable.class.isAssignableFrom(si.getTableInfo().getClassObj()))) {
        return;
    }

    if (debugUpdate) {
        printLevel(level);
        System.out.print(" -- ");
        System.out.println(si.getTableInfo() == null ? "Root" : si.getTableInfo().getName() + " -- ");
    }

    int cnt = 0;
    Vector<Integer> ids = null;
    if (si.getSql() != null && (si.isBuildingSQL() || si.isBuildingDelSQL())) {
        ids = new Vector<Integer>();
        String sql = si.isBuildingSQL() ? si.getSql() + Integer.toString(id) : si.getSql();

        if (debugUpdate)
            System.err.println(sql);

        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            int rowId = rs.getInt(1);
            ids.add(rowId);

            if (debugUpdate) {
                printLevel(level);
                System.out.println("Adding ID: " + rowId + "  "
                        + (si.getTableInfo() != null ? si.getTableInfo().getName() : "N/A"));
            }

            Statement statement = connection.createStatement();
            for (StackItem s : si.getStack()) {
                deleteRecords(s, level + 1, rowId, statement, doDeletes);
            }

            statement.close();
            cnt++;
        }
        rs.close();
        counter += cnt;

        if (debugUpdate) {
            //printLevel(level);
            System.err.println("Items returned: " + cnt);
        }
    }

    if (doDeletes) {
        if (si.isBuildingDelSQL()) {
            if (ids != null) {
                if (cnt > 0) {
                    for (Integer itemId : ids) {
                        if (si.getDelSql() != null) {
                            String delSql = si.getDelSql() + itemId;

                            if (StringUtils.contains(si.getDelSql(), "XXX")) {
                                delSql = StringUtils.replace(si.getDelSql(), "XXX", Integer.toString(itemId));
                            }

                            if (si.getTableInfo().getClassObj() == Discipline.class
                                    && StringUtils.contains(delSql, "FROM discipline")) {
                                deleteDiscipline(delSql, itemId);

                            } else {
                                if (si.getTableInfo().getClassObj() == Division.class
                                        && StringUtils.contains(delSql, "FROM division")) {
                                    cleanUpAgentsForDivision(id);
                                } else if (si.getTableInfo().getName().endsWith("attribute")) {
                                    String preDelSql = "update "
                                            + si.getTableInfo().getName().replace("attribute", "") + " set "
                                            + si.getTableInfo().getPrimaryKeyName() + " = null where "
                                            + si.getTableInfo().getPrimaryKeyName() + " = " + itemId;
                                    if (debugUpdate)
                                        System.err.println(preDelSql);
                                    int count = stmt.executeUpdate(preDelSql);
                                    if (debugUpdate)
                                        System.err.println("Count: " + count);

                                }

                                if (debugUpdate)
                                    System.err.println(delSql);
                                int count = stmt.executeUpdate(delSql);
                                if (debugUpdate)
                                    System.err.println("Count: " + count);
                            }

                        }
                    }
                }
            } else if (si.getDelSql() != null) {
                String delSql = si.getDelSql() + id;
                if (debugUpdate)
                    System.err.println(delSql);

                int count = stmt.executeUpdate(delSql);
                if (debugUpdate)
                    System.err.println("Count: " + count);
            }
        } else if (si.getDelSql() != null) {
            String delSql = si.getDelSql();
            if (debugUpdate)
                System.err.println("*****: " + delSql);

            int count = stmt.executeUpdate(delSql);
            if (debugUpdate)
                System.err.println("Count: " + count);
        }

        for (StackItem stckItm : si.getPostProcStack()) {
            deleteRecords(stckItm, level + 2, id, stmt, true);
        }
    }

    if (debugUpdate) {
        printLevel(level);
        System.out.println("Records to delete: " + cnt);
    }

    if (totalCount != null && debugUpdate) {
        System.err.println(counter + " / " + totalCount);
    }

    if (worker != null && totalCount != null) {
        worker.firePropertyChange(CNT, totalCount, (int) ((100.0 * counter) / totalCount));
    }
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineService.java

/**
 * Will return the RuleType from package name.
 * @param packageName/*  w  w  w  .jav a2 s  .  c o  m*/
 * @return
 */
public RuleType parseRuleType(String packageName) {

    if (StringUtils.contains(packageName, "sae_reporting_rules"))
        return RuleType.REPORT_SCHEDULING_RULES;
    if (StringUtils.contains(packageName, "field_rules"))
        return RuleType.FIELD_LEVEL_RULES;
    if (StringUtils.contains(packageName, "mandatory_sections_rules"))
        return RuleType.MANDATORY_SECTIONS_RULES;
    if (StringUtils.contains(packageName, "safety_signalling_rules"))
        return RuleType.SAFETY_SIGNALLING_RULES;

    return null;
}

From source file:ch.cyberduck.core.Preferences.java

/**
 * @param locale ISO Language identifier
 * @return Human readable language name in the target language
 *//*from  www.  ja v  a2s  .c  o  m*/
public String getDisplayName(String locale) {
    java.util.Locale l;
    if (StringUtils.contains(locale, "_")) {
        l = new java.util.Locale(locale.split("_")[0], locale.split("_")[1]);
    } else {
        l = new java.util.Locale(locale);
    }
    return StringUtils.capitalize(l.getDisplayName(l));
}

From source file:it.govpay.web.rs.dars.anagrafica.tributi.TipiTributoHandler.java

@Override
public void checkEntry(TipoTributo entry, TipoTributo oldEntry) throws ValidationException {
    if (entry == null || entry.getCodTributo() == null || entry.getCodTributo().isEmpty()) {
        throw new ValidationException(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreCodTributoObbligatorio"));
    }//  www. j  a  v a  2 s.co  m
    if (entry == null || entry.getDescrizione() == null || entry.getDescrizione().isEmpty()) {
        throw new ValidationException(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreDecrizioneObbligatoria"));
    }
    if (entry == null || entry.getTipoContabilitaDefault() == null) {
        throw new ValidationException(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                this.nomeServizio + ".creazione.erroreTipoContabilitaObbligatorio"));
    }
    if (entry == null || entry.getCodContabilitaDefault() == null
            || entry.getCodContabilitaDefault().isEmpty()) {
        throw new ValidationException(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                this.nomeServizio + ".creazione.erroreCodContabilitaObbligatorio"));
    }
    if (StringUtils.contains(entry.getCodContabilitaDefault(), " ")) {
        throw new ValidationException(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".creazione.erroreCodContabilitaNoSpazi"));
    }

    if (oldEntry != null) {
        if (!entry.getCodTributo().equals(oldEntry.getCodTributo())) {
            throw new ValidationException(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                    this.nomeServizio + ".aggiornamento.erroreCodTributoModificato"));
        }
    }
}

From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java

/**
 * Creates a single ActionConfig object.
 *
 * @param pkgCfg       The package the action configuration instance will belong to.
 * @param actionClass  The action class.
 * @param actionName   The name of the action.
 * @param actionMethod The method that the annotation was on (if the annotation is not null) or
 *                     the default method (execute).
 * @param annotation   The ActionName annotation that might override the action name and possibly
 *//*  w w  w.  j  a  v a2  s.c o  m*/
protected void createActionConfig(PackageConfig.Builder pkgCfg, Class<?> actionClass, String actionName,
        String actionMethod, Action annotation) {
    if (annotation != null) {
        actionName = annotation.value() != null && annotation.value().equals(Action.DEFAULT_VALUE) ? actionName
                : annotation.value();
        actionName = StringUtils.contains(actionName, "/") ? StringUtils.substringAfterLast(actionName, "/")
                : actionName;
    }

    ActionConfig.Builder actionConfig = new ActionConfig.Builder(pkgCfg.getName(), actionName,
            actionClass.getName());
    actionConfig.methodName(actionMethod);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating action config for class [" + actionClass.toString() + "], name [" + actionName
                + "] and package name [" + pkgCfg.getName() + "] in namespace [" + pkgCfg.getNamespace() + "]");
    }

    //build interceptors
    List<InterceptorMapping> interceptors = interceptorMapBuilder.build(actionClass, pkgCfg, actionName,
            annotation);
    actionConfig.addInterceptors(interceptors);

    //build results
    Map<String, ResultConfig> results = resultMapBuilder.build(actionClass, annotation, actionName,
            pkgCfg.build());
    actionConfig.addResultConfigs(results);

    //add params
    if (annotation != null)
        actionConfig.addParams(StringTools.createParameterMap(annotation.params()));

    //add exception mappings from annotation
    if (annotation != null && annotation.exceptionMappings() != null)
        actionConfig.addExceptionMappings(buildExceptionMappings(annotation.exceptionMappings(), actionName));

    //add exception mapping from class
    ExceptionMappings exceptionMappings = actionClass.getAnnotation(ExceptionMappings.class);
    if (exceptionMappings != null)
        actionConfig.addExceptionMappings(buildExceptionMappings(exceptionMappings.value(), actionName));

    //add
    pkgCfg.addActionConfig(actionName, actionConfig.build());

    //check if an action with the same name exists on that package (from XML config probably)
    PackageConfig existingPkg = configuration.getPackageConfig(pkgCfg.getName());
    if (existingPkg != null) {
        // there is a package already with that name, check action
        ActionConfig existingActionConfig = existingPkg.getActionConfigs().get(actionName);
        if (existingActionConfig != null && LOG.isWarnEnabled())
            LOG.warn("Duplicated action definition in package [#0] with name [#1].", pkgCfg.getName(),
                    actionName);
    }

    //watch class file
    if (isReloadEnabled()) {
        URL classFile = actionClass.getResource(actionClass.getSimpleName() + ".class");
        FileManager.loadFile(classFile, false);
        loadedFileUrls.add(classFile.toString());
    }
}

From source file:com.impetus.client.cassandra.query.CassQuery.java

/**
 * Append order by clause.//from w w  w  . j  ava 2s .c  o  m
 * 
 * @param metaModel
 *            the meta model
 * @param m
 *            the m
 * @param keyObj
 *            the key obj
 * @param builder
 *            the builder
 * @param translator
 *            the translator
 * @return the string builder
 */
private StringBuilder appendOrderByClause(MetamodelImpl metaModel, EntityMetadata m, EmbeddableType keyObj,
        StringBuilder builder, CQLTranslator translator) {
    List<SortOrdering> orders = getKunderaQuery().getOrdering();

    if (orders != null) {
        builder.append(CQLTranslator.SPACE_STRING);
        builder.append(CQLTranslator.SORT_CLAUSE);

        for (SortOrdering order : orders) {
            String orderColumnName = order.getColumnName();

            orderColumnName = orderColumnName.substring(orderColumnName.indexOf(".") + 1,
                    orderColumnName.length());

            String orderByColumnName;

            if (StringUtils.contains(orderColumnName, '.')) {
                String propertyName = orderColumnName.substring(0, orderColumnName.indexOf("."));
                Attribute embeddableAttribute = metaModel.getEntityAttribute(m.getEntityClazz(), propertyName);
                EmbeddableType embeddableType = metaModel
                        .embeddable(((AbstractAttribute) embeddableAttribute).getBindableJavaType());
                orderColumnName = orderColumnName.substring(orderColumnName.indexOf(".") + 1);
                AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(orderColumnName);
                orderByColumnName = attribute.getJPAColumnName();

            } else {
                Attribute attribute = metaModel.getEntityAttribute(m.getEntityClazz(), orderColumnName);
                orderByColumnName = ((AbstractAttribute) attribute).getJPAColumnName();
            }

            builder = translator.ensureCase(builder, orderByColumnName, false);
            builder.append(CQLTranslator.SPACE_STRING);
            builder.append(order.getOrder());
            builder.append(CQLTranslator.COMMA_STR);
        }

        if (!orders.isEmpty()) {
            builder.deleteCharAt(builder.lastIndexOf(CQLTranslator.COMMA_STR));
        }
    }
    return builder;
}