List of usage examples for java.sql ResultSet getFloat
float getFloat(String columnLabel) throws SQLException;
ResultSet
object as a float
in the Java programming language. From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java
@SuppressWarnings("deprecation") @Test/* w w w . j a v a 2s .co m*/ public void testResultSetWhenClosed() throws Exception { Statement statement = getConnection().createStatement(); ResultSet rs = statement.executeQuery(SQL_EMPS); rs.close(); try { rs.isBeforeFirst(); fail(); } catch (SQLException ignore) { } try { rs.isAfterLast(); fail(); } catch (SQLException ignore) { } try { rs.isFirst(); fail(); } catch (SQLException ignore) { } try { rs.isLast(); fail(); } catch (SQLException ignore) { } try { rs.beforeFirst(); fail(); } catch (SQLException ignore) { } try { rs.afterLast(); fail(); } catch (SQLException ignore) { } try { rs.first(); fail(); } catch (SQLException ignore) { } try { rs.last(); fail(); } catch (SQLException ignore) { } try { rs.next(); fail(); } catch (SQLException ignore) { } try { rs.getRow(); fail(); } catch (SQLException ignore) { } try { rs.getType(); fail(); } catch (SQLException ignore) { } try { rs.getConcurrency(); fail(); } catch (SQLException ignore) { } try { rs.rowUpdated(); fail(); } catch (SQLException ignore) { } try { rs.rowDeleted(); fail(); } catch (SQLException ignore) { } try { rs.rowInserted(); fail(); } catch (SQLException ignore) { } try { rs.getStatement(); fail(); } catch (SQLException ignore) { } try { rs.wasNull(); fail(); } catch (SQLException ignore) { } try { rs.getString(1); fail(); } catch (SQLException ignore) { } try { rs.getString("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBoolean(1); fail(); } catch (SQLException ignore) { } try { rs.getBoolean("col1"); fail(); } catch (SQLException ignore) { } try { rs.getByte(1); fail(); } catch (SQLException ignore) { } try { rs.getByte("col1"); fail(); } catch (SQLException ignore) { } try { rs.getShort(1); fail(); } catch (SQLException ignore) { } try { rs.getShort("col1"); fail(); } catch (SQLException ignore) { } try { rs.getInt(1); fail(); } catch (SQLException ignore) { } try { rs.getInt("col1"); fail(); } catch (SQLException ignore) { } try { rs.getLong(1); fail(); } catch (SQLException ignore) { } try { rs.getLong("col1"); fail(); } catch (SQLException ignore) { } try { rs.getFloat(1); fail(); } catch (SQLException ignore) { } try { rs.getFloat("col1"); fail(); } catch (SQLException ignore) { } try { rs.getDouble(1); fail(); } catch (SQLException ignore) { } try { rs.getDouble("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBigDecimal(1); fail(); } catch (SQLException ignore) { } try { rs.getBigDecimal("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBytes(1); fail(); } catch (SQLException ignore) { } try { rs.getBytes("col1"); fail(); } catch (SQLException ignore) { } try { rs.getDate(1); fail(); } catch (SQLException ignore) { } try { rs.getDate(1, null); fail(); } catch (SQLException ignore) { } try { rs.getDate("col1"); fail(); } catch (SQLException ignore) { } try { rs.getDate("col1", null); fail(); } catch (SQLException ignore) { } try { rs.getTime(1); fail(); } catch (SQLException ignore) { } try { rs.getTime(1, null); fail(); } catch (SQLException ignore) { } try { rs.getTime("col1"); fail(); } catch (SQLException ignore) { } try { rs.getTime("col1", null); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp(1); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp(1, null); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp("col1"); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp("col1", null); fail(); } catch (SQLException ignore) { } try { rs.getAsciiStream(1); fail(); } catch (SQLException ignore) { } try { rs.getAsciiStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getUnicodeStream(1); fail(); } catch (SQLException ignore) { } try { rs.getUnicodeStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBinaryStream(1); fail(); } catch (SQLException ignore) { } try { rs.getBinaryStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getCharacterStream(1); fail(); } catch (SQLException ignore) { } try { rs.getCharacterStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getMetaData(); fail(); } catch (SQLException ignore) { } try { rs.setFetchDirection(1); fail(); } catch (SQLException ignore) { } try { rs.getFetchDirection(); fail(); } catch (SQLException ignore) { } try { rs.setFetchSize(100); fail(); } catch (SQLException ignore) { } try { rs.getFetchSize(); fail(); } catch (SQLException ignore) { } try { rs.getHoldability(); fail(); } catch (SQLException ignore) { } statement.close(); }
From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java
/** * @param dbdriverInfo/* w w w.j a va 2s . c o m*/ * @param hostname * @param databaseName * @param userName * @param password * @return * @throws SQLException */ private boolean manuallyFixDB(final DatabaseDriverInfo dbdriverInfo, final String hostname, final String databaseName, final String userName, final String password) throws SQLException { frame.setOverall(0, OVERALL_TOTAL); // 23 + 7 + String connectionStr = dbdriverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostname, databaseName, true, true, userName, password, dbdriverInfo.getName()); log.debug("generateSchema connectionStr: " + connectionStr); log.debug("Creating database connection to: " + connectionStr); // Now connect to other databases and "create" the Derby database DBConnection dbConn = null; try { dbConn = DBConnection.createInstance(dbdriverInfo.getDriverClassName(), dbdriverInfo.getDialectClassName(), databaseName, connectionStr, userName, password); if (dbConn != null && dbConn.getConnection() != null) { Connection conn = dbConn.getConnection(); Statement stmt = null; try { stmt = conn.createStatement(); Integer count = null; int rv = 0; //--------------------------------------------------------------------------- //-- LocalityDetail //--------------------------------------------------------------------------- String tblName = getTableNameAndTitleForFrame(LocalityDetail.getClassTableId()); Integer len = getFieldLength(conn, databaseName, tblName, "UtmDatum"); if (len == null) { count = getCount(tblName); rv = update(conn, "ALTER TABLE localitydetail CHANGE getUtmDatum UtmDatum varchar(255)"); if (rv != count) { errMsgList.add("Unable to alter table: localitydetail"); return false; } } else { if (len.intValue() != 255) { count = getCount(tblName); rv = update(conn, "ALTER TABLE localitydetail MODIFY UtmDatum varchar(255)"); if (rv != count) { errMsgList.add("Unable to alter table: localitydetail"); return false; } } } frame.incOverall(); //--------------------------------------------------------------------------- //-- SpecifyUser //--------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(SpecifyUser.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, "Password"); if (len == null) { errMsgList.add(String.format("Unable to update table: %", tblName)); return false; } if (len.intValue() != 255) { count = getCount(tblName); rv = update(conn, "ALTER TABLE specifyuser MODIFY Password varchar(255)"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } frame.incOverall(); //--------------------------------------------------------------------------- //-- SpExportSchemaItem //--------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(SpExportSchemaItem.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, "FieldName"); if (len == null) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } if (len.intValue() != 64) { count = BasicSQLUtils.getCount("SELECT COUNT(*) FROM spexportschemaitem"); rv = update(conn, "ALTER TABLE spexportschemaitem MODIFY FieldName varchar(64)"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } frame.incOverall(); //--------------------------------------------------------------------------- //-- Agent //--------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(Agent.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, "LastName"); if (len == null) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } if (len.intValue() != 128) { count = getCount(tblName); rv = update(conn, "ALTER TABLE agent MODIFY LastName varchar(128)"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } frame.incOverall(); //--------------------------------------------------------------------------- //-- SpExportSchema //--------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(SpExportSchema.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, "SchemaName"); if (len == null) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } if (len.intValue() != 80) { count = getCount(tblName); rv = update(conn, "ALTER TABLE spexportschema MODIFY SchemaName varchar(80)"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } frame.incOverall(); len = getFieldLength(conn, databaseName, tblName, "SchemaVersion"); if (len == null) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } if (len.intValue() != 80) { count = getCount(tblName); rv = update(conn, "ALTER TABLE spexportschema MODIFY SchemaVersion varchar(80)"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } frame.incOverall(); // String checkSQL = "select SpExportSchemaMappingID, MappingName from spexportschemamapping " // + "where CollectionMemberID is null"; // Vector<Object[]> mappingsToFix = BasicSQLUtils.query(checkSQL); // if (mappingsToFix != null && mappingsToFix.size() > 0) // { // Vector<Object> collectionIDs = BasicSQLUtils.querySingleCol("select UserGroupScopeID from collection"); // if (collectionIDs.size() == 1) // { // //easy // BasicSQLUtils.update("update spexportschemamapping set CollectionMemberID = " + collectionIDs.get(0)); // } // else // { // for (Object[] row : mappingsToFix) // { // log.info("fixing mappings in multiple collection database"); // String cacheName = ExportToMySQLDB.fixTblNameForMySQL(row[1].toString()); // if (BasicSQLUtils.doesTableExist(DBConnection.getInstance().getConnection(), cacheName)) // { // String cacheID = cacheName + "ID"; // String sql = "select distinct CollectionMemberID from collectionobject co inner join " // + cacheName + " cn on cn." + cacheID + " = co.CollectionObjectID"; // Vector<Object> collsInCache = BasicSQLUtils.querySingleCol(sql); // if (collsInCache != null && collsInCache.size() == 1) // { // //easy // String updateSQL = "update spexportschemamapping set CollectionMemberID = " + collsInCache.get(0) // + " where SpExportSchemaMappingID = " + row[0]; // log.info("Updating exportmapping with cache containing single collection: " + updateSQL); // BasicSQLUtils.update(updateSQL); // // } else if (collsInCache != null && collsInCache.size() > 1) // { // //This should never happen, but if it does, should ask user to choose. // //Also need to update TimestampModified to force rebuild of cache... // //but... // String updateSQL = "update spexportschemamapping set CollectionMemberID = " + collsInCache.get(0) // + " where SpExportSchemaMappingID = " + row[0]; // log.info("Updating exportmapping with cache containing multiple collections: " + updateSQL); // BasicSQLUtils.update(updateSQL); // } // // } else // { // log.info("updating export mapping that has no cache: " + row[1] + " - " + row[0]); // String discSQL = "select distinct DisciplineID from spexportschema es inner join spexportschemaitem esi " // + "on esi.SpExportSchemaID = es.SpExportSchemaID inner join spexportschemaitemmapping esim " // + "on esim.ExportSchemaItemID = esi.SpExportSchemaItemID where esim.SpExportSchemaMappingID " // + "= " + row[0]; // Object disciplineID = BasicSQLUtils.querySingleObj(discSQL); // if (disciplineID != null) // { // String discCollSql = "select UserGroupScopeID from collection where DisciplineID = " + disciplineID; // Vector<Object> collIDsInDisc = BasicSQLUtils.querySingleCol(discCollSql); // if (collIDsInDisc != null && collIDsInDisc.size() == 1) // { // //easy // String updateSQL = "update spexportschemamapping set CollectionMemberID = " + collIDsInDisc.get(0) // + " where SpExportSchemaMappingID = " + row[0]; // log.info("Updating exportmapping that has no cache and one collection in its discipline: " + updateSQL); // BasicSQLUtils.update(updateSQL); // // } else if (collIDsInDisc != null && collIDsInDisc.size() > 1) // { // //Picking the first collection. How likely is it to matter? Not very. // String updateSQL = "update spexportschemamapping set CollectionMemberID = " + collIDsInDisc.get(0) // + " where SpExportSchemaMappingID = " + row[0]; // log.info("Updating exportmapping that has no cache and a discipline with multiple collections: " + updateSQL); // BasicSQLUtils.update(updateSQL); // } // } else // { // throw new Exception("unable to find discipline for exportschemamapping " + row[0]); // } // // } // } // } // //AppPreferences.getGlobalPrefs().putBoolean("FixExportSchemaCollectionMemberIDs", true); // } // frame.incOverall(); //--------------------------------------------------------------------------- //-- SpecifySchemaUpdateScopeFixer //--------------------------------------------------------------------------- SpecifySchemaUpdateScopeFixer collectionMemberFixer = new SpecifySchemaUpdateScopeFixer( databaseName); if (!collectionMemberFixer.fix(conn)) { errMsgList.add("Error fixing CollectionMember tables"); return false; } // Do updates for Schema 1.2 doFixesForDBSchemaVersions(conn, databaseName); // increments 7 times // Find Accession NumberingSchemes that 'attached' to Collections String postfix = " FROM autonumsch_coll ac Inner Join autonumberingscheme ans ON ac.AutoNumberingSchemeID = ans.AutoNumberingSchemeID WHERE ans.TableNumber = '7'"; log.debug("SELECT COUNT(*)" + postfix); count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*)" + postfix); if (count > 0) { // Get the Format name being used for each Collection's Access Number Hashtable<Integer, String> collIdToFormatHash = new Hashtable<Integer, String>(); String sql = "SELECT c.UserGroupScopeId, ci.`Format` FROM collection c Inner Join discipline d ON c.DisciplineID = d.UserGroupScopeId " + "Inner Join splocalecontainer cn ON d.UserGroupScopeId = cn.DisciplineID " + "Inner Join splocalecontaineritem ci ON cn.SpLocaleContainerID = ci.SpLocaleContainerID " + "WHERE ci.Name = 'accessionNumber'"; for (Object[] row : query(conn, sql)) { collIdToFormatHash.put((Integer) row[0], row[1].toString()); // Key -> CollId, Value -> Format } String ansSQL = "SELECT ac.CollectionID, ac.AutoNumberingSchemeID " + postfix; log.debug(ansSQL); int totCnt = 0; for (Object[] row : query(conn, ansSQL)) { sql = "DELETE FROM autonumsch_coll WHERE CollectionID = " + ((Integer) row[0]) + " AND AutoNumberingSchemeID = " + ((Integer) row[1]); log.debug(sql); rv = update(conn, sql); if (rv != 1) { errMsgList.add( "There was an error fixing the table: autonumsch_coll for CollectionID = " + ((Integer) row[0]) + " AND AutoNumberingSchemeID = " + ((Integer) row[1])); } totCnt++; } if (totCnt != count) { errMsgList.add("There was an error fixing the table: autonumsch_coll"); } else { rv = count; } frame.incOverall(); } else { rv = count; } if (rv != count) { return false; } //--------------------------------------------------------------------------- //-- Fixing //--------------------------------------------------------------------------- String sql = "SELECT COUNT(d.UserGroupScopeId) CNT, d.UserGroupScopeId FROM division d INNER JOIN autonumsch_div ad ON d.UserGroupScopeId = ad.DivisionID " + "INNER JOIN autonumberingscheme ans ON ad.AutoNumberingSchemeID = ans.AutoNumberingSchemeID GROUP BY d.UserGroupScopeId"; log.debug(sql); for (Object[] row : query(conn, sql)) { Integer divId = ((Integer) row[1]); if (((Long) row[0]) > 1) { sql = "SELECT dv.UserGroupScopeId AS divId, ds.UserGroupScopeId AS dispId, ci.Name, ci.`Format` FROM division dv " + "Inner Join discipline ds ON dv.UserGroupScopeId = ds.DivisionID " + "Inner Join splocalecontainer c ON ds.UserGroupScopeId = c.DisciplineID " + "Inner Join splocalecontaineritem ci ON c.SpLocaleContainerID = ci.SpLocaleContainerID " + "WHERE ci.Name = 'accessionNumber' AND dv.UserGroupScopeId = " + divId; Vector<String> namesList = new Vector<String>(); Hashtable<String, Integer> formatNames = new Hashtable<String, Integer>(); for (Object[] innerRow : query(conn, sql)) { String formatName = innerRow[3].toString(); Integer dsid = (Integer) innerRow[1]; if (formatNames.get(formatName) == null) { formatNames.put(formatName, dsid); namesList.add(formatName); } } String desc = "<html>Accessions belong to the same Division. They must all share the same formatter.<BR>" + "Please choose a format below that will be the for your Division.<BR>"; ChooseFromListDlg<String> dlg = new ChooseFromListDlg<String>( (Frame) UIRegistry.getTopWindow(), "Choose a Format", desc, ChooseFromListDlg.OK_BTN, namesList); dlg.setVisible(true); String newFormatName = dlg.getSelectedObject(); List<String> disciplineNameList = new ArrayList<String>(); sql = "SELECT ans.AutoNumberingSchemeID FROM division d INNER JOIN autonumsch_div ad ON d.UserGroupScopeId = ad.DivisionID " + "INNER JOIN autonumberingscheme ans ON ad.AutoNumberingSchemeID = ans.AutoNumberingSchemeID WHERE d.UserGroupScopeId = " + divId; log.debug(sql); int cnt = 0; for (Object idAnsObj : querySingleCol(conn, sql)) { Integer ansId = (Integer) idAnsObj; if (cnt > 0) { sql = "DELETE FROM autonumsch_div WHERE DivisionID = " + divId + " AND AutoNumberingSchemeID = " + ansId; if (update(conn, sql) != 1) { errMsgList.add( "There was an error fixing the table: autonumsch_div for DivisionID = " + divId + " AND AutoNumberingSchemeID = " + ansId); return false; } sql = "DELETE FROM autonumberingscheme WHERE AutoNumberingSchemeID = " + ansId; if (update(conn, sql) != 1) { errMsgList.add( "There was an error fixing the table: autonumberingscheme; removing AutoNumberingSchemeID = " + ansId); return false; } sql = "SELECT SpLocaleContainerItemID, ds.Name FROM splocalecontaineritem ci INNER JOIN splocalecontainer c ON ci.SpLocaleContainerID = c.SpLocaleContainerID " + "INNER JOIN discipline ds ON c.DisciplineID = ds.UserGroupScopeId " + "INNER JOIN division dv ON ds.DivisionID = dv.UserGroupScopeId " + "WHERE ci.Name = 'accessionNumber' AND dv.UserGroupScopeId = " + divId + " AND NOT (ci.`Format` = '" + newFormatName + "')"; log.debug(sql); for (Object[] idRow : query(conn, sql)) { Integer spItemId = (Integer) idRow[0]; String dispName = idRow[1].toString(); sql = "UPDATE splocalecontaineritem SET `Format`='" + newFormatName + "' WHERE SpLocaleContainerItemID = " + spItemId; log.debug(sql); if (update(conn, sql) == 1) { disciplineNameList.add(dispName); } else { log.error("Error changing formatter name."); } } } cnt++; } desc = "<html>The following Disciplines have had their Accession Number formatter changed.<BR>" + "This change may require some Accession Numbers to be changed.<BR>" + "Please contact Specify Customer Support for additional help.<BR>"; dlg = new ChooseFromListDlg<String>((Frame) UIRegistry.getTopWindow(), "Accession Number Changes", desc, ChooseFromListDlg.OK_BTN, disciplineNameList); dlg.createUI(); dlg.getOkBtn().setEnabled(true); dlg.setVisible(true); } } frame.incOverall(); //----------------------------------------------------------------------------- //-- This will fix any Agents messed up by creating new Divisions //----------------------------------------------------------------------------- frame.setDesc("Fixing User's Agents..."); // I18N fixAgentsDivsDisps(conn); frame.incOverall(); //fixSpUserAndAgents(); //----------------------------------------------------------------------------- //-- This will add any new fields to the schema //----------------------------------------------------------------------------- //System.setProperty("AddSchemaTablesFields", "TRUE"); //fixLocaleSchema(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Schema Changes 1.4 // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (BasicSQLUtils.doesTableExist(conn, "agent_discipline")) { PreparedStatement pStmt = null; try { pStmt = conn.prepareStatement("UPDATE agent SET DivisionID=? WHERE AgentID = ?"); sql = "SELECT a.AgentID, d.DivisionID FROM agent AS a " + "Inner Join agent_discipline AS ad ON a.AgentID = ad.AgentID " + "Inner Join discipline AS d ON ad.DisciplineID = d.UserGroupScopeId " + "WHERE a.DivisionID IS NULL"; for (Object[] row : query(conn, sql)) { int agtId = (Integer) row[0]; int divId = (Integer) row[1]; pStmt.setInt(1, divId); pStmt.setInt(2, agtId); pStmt.executeUpdate(); } } catch (Exception e1) { e1.printStackTrace(); } finally { try { if (pStmt != null) { pStmt.close(); } } catch (Exception ex) { } } update(conn, "DROP TABLE agent_discipline"); } frame.incOverall(); //----------------------------------------------------------------------------- //-- Agent //----------------------------------------------------------------------------- // Add New Fields to Address tblName = getTableNameAndTitleForFrame(Agent.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "DateType")) { String[] addrCols = { "DateType", TINYINT4, "Title", "DateOfBirthPrecision", TINYINT4, "DateOfBirth", "DateOfDeathPrecision", TINYINT4, "DateOfDeath" }; if (!checkAndAddColumns(conn, databaseName, tblName, addrCols)) { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- Address //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(Address.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "Address3")) { frame.setDesc("Updating Address Fields..."); String fmtStr = "ALTER TABLE address ADD COLUMN Address%d VARCHAR(64) AFTER Address%d"; for (int i = 3; i < 6; i++) { update(conn, String.format(fmtStr, i, i - 1)); } } frame.incOverall(); //----------------------------------------------------------------------------- //-- LocalityDetail //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(LocalityDetail.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "StartDepth")) { String[] locDetCols = { "StartDepth", "Double", "Drainage", "StartDepthUnit", TINYINT4, "StartDepth", "StartDepthVerbatim", "VARCHAR(32)", "StartDepthUnit", "EndDepth", "Double", "StartDepthVerbatim", "EndDepthUnit", TINYINT4, "EndDepth", "EndDepthVerbatim", "VARCHAR(32)", "EndDepthUnit" }; if (!checkAndAddColumns(conn, databaseName, tblName, locDetCols)) { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- Locality //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(Locality.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "Text1")) { String[] locCols = { "Text1", "VARCHAR(255)", "SrcLatLongUnit", "Text2", "VARCHAR(255)", "Text1" }; if (!checkAndAddColumns(conn, databaseName, tblName, locCols)) { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- CollectionObjectAttribute //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(CollectionObjectAttribute.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "Text15")) { if (!addColumn(conn, databaseName, tblName, "Text15", "VARCHAR(64)", "Text14")) { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- PaleoContext //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(PaleoContext.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "ChronosStratEndID")) { if (!addColumn(conn, databaseName, tblName, "ChronosStratEndID", "INT", "ChronosStratID")) { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- Institution //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(Institution.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "IsSingleGeographyTree")) { String[] instCols = { "IsSingleGeographyTree", "BIT(1)", "IsServerBased", "IsSharingLocalities", "BIT(1)", "IsSingleGeographyTree" }; if (checkAndAddColumns(conn, databaseName, tblName, instCols)) { update(conn, "UPDATE institution SET IsSingleGeographyTree=0, IsSharingLocalities=0"); } else { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- GeologicTimePeriod //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(GeologicTimePeriod.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "Text1")) { String[] gtpCols = { "Text1", "VARCHAR(64)", "EndUncertainty", "Text2", "VARCHAR(64)", "Text1" }; if (!checkAndAddColumns(conn, databaseName, tblName, gtpCols)) { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- PreparationAttribute //----------------------------------------------------------------------------- // Fix Field Length tblName = getTableNameAndTitleForFrame(PreparationAttribute.getClassTableId()); String prepAttrFld = "Text22"; len = getFieldLength(conn, databaseName, tblName, prepAttrFld); if (len != null && len == 10) { alterFieldLength(conn, databaseName, tblName, prepAttrFld, 10, 50); } frame.incOverall(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Schema Changes 1.5 // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //BasicSQLUtils.update(conn, "UPDATE agent SET Title='mr' WHERE AgentType = 1 AND Title is NULL OR Title = ''"); //----------------------------------------------------------------------------- //-- GeoCoordDetail //----------------------------------------------------------------------------- // Change column types for MaxUncertaintityEst and NamedPlaceExtent tblName = getTableNameAndTitleForFrame(GeoCoordDetail.getClassTableId()); String columnType = getFieldColumnType(conn, databaseName, tblName, "MaxUncertaintyEst"); if (columnType == null) { errMsgList.add(String.format(COL_TYP_NO_DET, tblName)); return false; } if (!columnType.trim().equalsIgnoreCase("DECIMAL(20,10)")) { count = getCount(tblName); rv = update(conn, "ALTER TABLE geocoorddetail CHANGE COLUMN `MaxUncertaintyEst` `MaxUncertaintyEst` DECIMAL(20,10) NULL DEFAULT NULL, " + "CHANGE COLUMN `NamedPlaceExtent` `NamedPlaceExtent` DECIMAL(20,10) NULL DEFAULT NULL"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } sql = "SELECT COUNT(*) FROM geocoorddetail WHERE AgentID IS NULL"; int total = BasicSQLUtils.getCountAsInt(conn, sql); if (total > 0) { sql = "UPDATE geocoorddetail SET AgentID=CreatedByAgentID WHERE AgentID IS NULL"; rv = update(conn, sql); } frame.incOverall(); //----------------------------------------------------------------------------- //-- LoanPreparation //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(LoanPreparation.getClassTableId()); columnType = getFieldColumnType(conn, databaseName, tblName, "DescriptionOfMaterial"); if (columnType == null) { errMsgList.add(String.format(COL_TYP_NO_DET, tblName)); return false; } if (!columnType.trim().equalsIgnoreCase("text")) { count = getCount(tblName); rv = update(conn, String.format("ALTER TABLE %s MODIFY DescriptionOfMaterial TEXT", tblName)); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- ConservEvent //----------------------------------------------------------------------------- tblName = getTableNameAndTitleForFrame(ConservEvent.getClassTableId()); if (!doesColumnExist(databaseName, tblName, "Text1")) { String[] consrvEvCols = { "Text1", "VARCHAR(64)", "Remarks", "Text2", "VARCHAR(64)", "Text1", "Number1", INT11, "Text2", "Number2", INT11, "Number1", "YesNo1", "BIT(1)", "Number2", "YesNo2", "BIT(1)", "YesNo1", }; if (!checkAndAddColumns(conn, databaseName, tblName, consrvEvCols)) { return false; } } frame.incOverall(); //----------------------------------------------------------------------------- //-- DNASequencingRun //----------------------------------------------------------------------------- String runByAgentID = "RunByAgentID"; tblName = getTableNameAndTitleForFrame(DNASequencingRun.getClassTableId()); if (!doesColumnExist(databaseName, tblName, runByAgentID)) { if (addColumn(conn, databaseName, tblName, runByAgentID, INT11, "DNASequenceID")) { update(conn, "ALTER TABLE dnasequencingrun ADD KEY `FKDNASEQRUNRUNBYAGT` (`RunByAgentID`)"); update(conn, "ALTER TABLE dnasequencingrun ADD CONSTRAINT `FKDNASEQRUNRUNBYAGT` FOREIGN KEY (`RunByAgentID`) REFERENCES `agent` (`AgentID`)"); if (addColumn(conn, databaseName, tblName, "PreparedByAgentID", INT11, "RunByAgentID")) { update(conn, "ALTER TABLE dnasequencingrun ADD KEY `FKDNASEQRUNPREPBYAGT` (`PreparedByAgentID`)"); update(conn, "ALTER TABLE dnasequencingrun ADD CONSTRAINT `FKDNASEQRUNPREPBYAGT` FOREIGN KEY (`PreparedByAgentID`) REFERENCES `agent` (`AgentID`)"); } else { return false; } } else { return false; } } String pwdMinLen = "MinimumPwdLength"; tblName = getTableNameAndTitleForFrame(Institution.getClassTableId()); if (!doesColumnExist(databaseName, tblName, pwdMinLen)) { if (!addColumn(conn, databaseName, tblName, pwdMinLen, TINYINT4, "LsidAuthority")) { return false; } } frame.incOverall(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Schema Changes 1.6 // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// createSGRTables(conn, databaseName); frame.incOverall(); if (!miscSchema16Updates(conn, databaseName)) // Steps 26 - 28 { return false; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Schema Changes 1.7 // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// tblName = getTableNameAndTitleForFrame(SpQuery.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, "SqlStr"); if (len == 64) { if (!fixSpQuerySQLLength(conn, databaseName)) { return false; } } frame.incOverall(); frame.setProcess(0, 100); //----------------------------------------------------------------------------- //-- Determination fix //----------------------------------------------------------------------------- String varQualNameBad = "VarQualifer"; String varQualNameGood = "VarQualifier"; tblName = getTableNameAndTitleForFrame(Determination.getClassTableId()); if (doesColumnExist(databaseName, tblName, varQualNameBad) && !doesColumnExist(databaseName, tblName, varQualNameGood)) { if (addColumn(conn, databaseName, tblName, varQualNameGood, "VARCHAR(16)", "TypeStatusName")) { update(conn, String.format("UPDATE determination SET %s=%s WHERE %s IS NOT NULL", varQualNameGood, varQualNameBad, varQualNameBad)); update(conn, String.format("ALTER TABLE determination DROP COLUMN %s", varQualNameBad)); update(conn, String.format("UPDATE splocalecontaineritem SET Name='%s' WHERE Name = '%s'", varQualNameGood, varQualNameBad)); } else { return false; } } //----------------------------------------------------------------------------- // Fix Bug 8747 - PickList item has wrong value //----------------------------------------------------------------------------- String updateStr = "UPDATE picklistitem SET Value = 'exisotype' WHERE Title = 'Ex Isotype' AND Value = 'isotype'"; BasicSQLUtils.update(updateStr); frame.setProcess(0, 100); frame.incOverall(); //----------------------------------------------------------------------------- // Adds new OCR field to CollectionObject //----------------------------------------------------------------------------- frame.setDesc("Adding OCR field to Collection Object"); // I18N String ocrField = "OCR"; tblName = getTableNameAndTitleForFrame(CollectionObject.getClassTableId()); if (!doesColumnExist(databaseName, tblName, ocrField)) { if (!addColumn(conn, databaseName, tblName, ocrField, "TEXT", "TotalValue")) { return false; } } frame.setProcess(0, 100); frame.incOverall(); updateDNAAttachments(conn); frame.setProcess(0, 100); frame.incOverall(); // Fix indexes if (doesIndexExist("borrowagent", "BorColMemIDX")) { update(conn, "DROP INDEX BorColMemIDX on borrowagent"); update(conn, "CREATE INDEX BorColMemIDX2 ON borrowagent(CollectionMemberID)"); } if (doesIndexExist("exchangeout", "DescriptionOfMaterialIDX")) { update(conn, "DROP INDEX DescriptionOfMaterialIDX on exchangeout"); update(conn, "CREATE INDEX DescriptionOfMaterialIDX2 ON exchangeout(DescriptionOfMaterial)"); } frame.incOverall(); frame.setProcess(0, 100); fixCollectorOrder(conn); // fixes the Ordinal number of Collectors frame.incOverall(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Schema Changes 1.8 // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int instID = BasicSQLUtils.getCountAsInt("SELECT InstitutionID FROM institution"); frame.setDesc("Updating Reference Work..."); // I18N String instName = "InstitutionID"; tblName = getTableNameAndTitleForFrame(ReferenceWork.getClassTableId()); if (!doesColumnExist(databaseName, tblName, instName)) { String updateSQL = "ALTER TABLE %s ADD COLUMN %s INT(11) NOT NULL AFTER JournalID"; if (addColumn(conn, databaseName, tblName, instName, updateSQL)) { update(conn, "ALTER TABLE referencework ADD KEY `FK5F7C68DC81223908` (`InstitutionID`)"); update(conn, String.format("UPDATE referencework SET InstitutionID=%d", instID)); update(conn, "ALTER TABLE referencework ADD CONSTRAINT `FK5F7C68DC81223908` FOREIGN KEY (`InstitutionID`) REFERENCES `institution` (`UserGroupScopeId`)"); } else { return false; } } frame.setProcess(0, 100); fixConservDescriptions(conn); frame.setDesc("Updating Journals..."); // I18N tblName = getTableNameAndTitleForFrame(Journal.getClassTableId()); if (!doesColumnExist(databaseName, tblName, instName)) { String updateSQL = "ALTER TABLE %s ADD COLUMN %s INT(11) NOT NULL AFTER Text1"; if (addColumn(conn, databaseName, tblName, instName, updateSQL)) { update(conn, "ALTER TABLE journal ADD KEY `FKAB64AF3781223908` (`InstitutionID`)"); update(conn, String.format("UPDATE journal SET InstitutionID=%d", instID)); update(conn, "ALTER TABLE journal ADD CONSTRAINT `FKAB64AF3781223908` FOREIGN KEY (`InstitutionID`) REFERENCES `institution` (`UserGroupScopeId`)"); } else { return false; } } frame.setProcess(0, 100); frame.incOverall(); frame.setDesc("Updating Permits..."); // I18N tblName = getTableNameAndTitleForFrame(Permit.getClassTableId()); if (!doesColumnExist(databaseName, tblName, instName)) { String updateSQL = "ALTER TABLE %s ADD COLUMN %s INT(11) NOT NULL AFTER IssuedToID"; if (addColumn(conn, databaseName, tblName, instName, updateSQL)) { update(conn, "ALTER TABLE permit ADD KEY `FKC4E3841B81223908` (`InstitutionID`)"); update(conn, String.format("UPDATE permit SET InstitutionID=%d", instID)); update(conn, "ALTER TABLE permit ADD CONSTRAINT `FKC4E3841B81223908` FOREIGN KEY (`InstitutionID`) REFERENCES `institution` (`UserGroupScopeId`)"); } else { return false; } } frame.setProcess(0, 100); frame.incOverall(); //----------------------------------------------------------------------------- //-- LocalityDetail //----------------------------------------------------------------------------- frame.setDesc("Updating Locality Detail..."); // I18N // Change column types for UTMEasting, UTMNorthing and UTMScale tblName = getTableNameAndTitleForFrame(LocalityDetail.getClassTableId()); String eastingColumnType = getFieldColumnType(conn, databaseName, tblName, "UTMEasting"); if (eastingColumnType == null) { errMsgList.add(String.format(COL_TYP_NO_DET, tblName)); return false; } if (!eastingColumnType.trim().equalsIgnoreCase("DECIMAL(19,2)")) { count = BasicSQLUtils .getCountAsInt("SELECT COUNT(*) FROM " + tblName + " where UtmEasting is not null"); if (count > 0) { File outFile = new File( UIRegistry.getAppDataDir() + File.separator + "localityDetailUtmEasting.txt"); try { PrintWriter pw = new PrintWriter(outFile); String q = "select localitydetailid, UtmEasting from localitydetail " + " where UtmEasting is not null"; ResultSet rs = stmt.executeQuery(q); while (rs.next()) { pw.write(String.format("%d\t%f\n", rs.getInt(1), rs.getFloat(2))); } rs.close(); pw.flush(); pw.close(); } catch (IOException ex) { ex.printStackTrace(); } } count = getCount(tblName); rv = update(conn, "ALTER TABLE localitydetail CHANGE COLUMN `UtmEasting` `UtmEasting` DECIMAL(19,2) NULL DEFAULT NULL"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } String northingColumnType = getFieldColumnType(conn, databaseName, tblName, "UTMNorthing"); if (northingColumnType == null) { errMsgList.add(String.format(COL_TYP_NO_DET, tblName)); return false; } if (!northingColumnType.trim().equalsIgnoreCase("DECIMAL(19,2)")) { count = BasicSQLUtils.getCountAsInt( "SELECT COUNT(*) FROM " + tblName + " where utmNorthing is not null"); if (count > 0) { File outFile = new File( UIRegistry.getAppDataDir() + File.separator + "localityDetailUtm.txt"); try { PrintWriter pw = new PrintWriter(outFile); String q = "select localitydetailid, UtmNorthing from localitydetail " + " where UtmNorthing is not null"; ResultSet rs = stmt.executeQuery(q); while (rs.next()) { pw.write(String.format("%d\t%f\n", rs.getInt(1), rs.getFloat(2))); } rs.close(); pw.flush(); pw.close(); } catch (IOException ex) { ex.printStackTrace(); } } count = getCount(tblName); rv = update(conn, "ALTER TABLE localitydetail CHANGE COLUMN `UtmNorthing` `UtmNorthing` DECIMAL(19,2) NULL DEFAULT NULL"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } String scaleColumnType = getFieldColumnType(conn, databaseName, tblName, "UTMScale"); if (scaleColumnType == null) { errMsgList.add(String.format(COL_TYP_NO_DET, tblName)); return false; } if (!scaleColumnType.trim().equalsIgnoreCase("DECIMAL(20,10)")) { count = BasicSQLUtils .getCountAsInt("SELECT COUNT(*) FROM " + tblName + " where UTMScale is not null"); if (count > 0) { File outFile = new File( UIRegistry.getAppDataDir() + File.separator + "localityDetailUtm.txt"); try { PrintWriter pw = new PrintWriter(outFile); String q = "select localitydetailid, UtmScale from localitydetail " + " where UtmScale is not null"; ResultSet rs = stmt.executeQuery(q); while (rs.next()) { pw.write(String.format("%d\t%f\n", rs.getInt(1), rs.getFloat(2))); } rs.close(); pw.flush(); pw.close(); } catch (IOException ex) { ex.printStackTrace(); } } count = getCount(tblName); rv = update(conn, "ALTER TABLE localitydetail CHANGE COLUMN `UtmScale` `UtmScale` DECIMAL(20,10) NULL DEFAULT NULL"); if (rv != count) { errMsgList.add(String.format(UPD_CNT_NO_MATCH, tblName)); return false; } } frame.incOverall(); //End LocalityDetail changes //////////////////////////////////////////////////////////////////////////////////////////////////////// frame.setProcess(0, 100); frame.incOverall(); Integer[] sgrTblIds = new Integer[] { CollectionObject.getClassTableId(), CollectingEvent.getClassTableId(), Locality.getClassTableId(), WorkbenchRow.getClassTableId() }; String[] sgrAfter = new String[] { "TotalValue", "Remarks", "Text2", "UploadStatus" }; String sgrStatusField = "SGRStatus"; int i = 0; for (Integer tblId : sgrTblIds) { tblName = getTableNameAndTitleForFrame(tblId); if (!doesColumnExist(databaseName, tblName, ocrField)) { if (!addColumn(conn, databaseName, tblName, sgrStatusField, TINYINT4, sgrAfter[i])) { return false; } } i++; } addNewAttachmentTables(conn); frame.setDesc("Adding ISO Code field to Geography"); // I18N String geoCode = "GeographyCode"; tblName = getTableNameAndTitleForFrame(Geography.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, geoCode); if (len != null && len == 8) { alterFieldLength(conn, databaseName, tblName, geoCode, 8, 24); } // Adding fields to the 'attachment' table and fill them in frame.setDesc("Adding TableID to Attachment Table"); // I18N if (!addTableIDToAttachmentTable(conn, databaseName)) { return false; } frame.setDesc("Adding and fixing Attachment scoping"); if (!addScopingToAttachmentTable(conn, databaseName)) { return false; } frame.setDesc("Fixing PDF mimetype in Attachment Table"); update(conn, "UPDATE attachment SET MimeType='application/pdf' " + "WHERE MimeType = 'application/octet-stream' " + "AND LOWER(SubStr(AttachmentLocation, LENGTH(AttachmentLocation) - 2, LENGTH(AttachmentLocation))) = 'pdf'"); tblName = getTableNameAndTitleForFrame(Attachment.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, "origFilename"); if (len != null && len == 128) { alterFieldLength(conn, databaseName, tblName, "origFilename", 128, 20000); } len = getFieldLength(conn, databaseName, tblName, "title"); if (len != null && len == 64) { alterFieldLength(conn, databaseName, tblName, "title", 64, 255); } frame.setDesc("Updating GUIDs"); // I18N if (!addGUIDCols(conn, databaseName)) { return false; } generateMissingGUIDs(frame); frame.incOverall(); // Setting new Field Length for QueryFields String startValue = "StartValue"; tblName = getTableNameAndTitleForFrame(SpQueryField.getClassTableId()); len = getFieldLength(conn, databaseName, tblName, startValue); if (len != null && len == 64) { alterFieldLength(conn, databaseName, tblName, startValue, 64, 255); } String endValue = "EndValue"; len = getFieldLength(conn, databaseName, tblName, endValue); if (len != null && len == 64) { alterFieldLength(conn, databaseName, tblName, endValue, 64, 255); } frame.incOverall(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Schema Changes 1.9 // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------- // spreport -- fix for bug #9414. //------------------------------------------------------------------- if (!getFieldNullability(conn, databaseName, "spreport", "SpQueryID")) { frame.setDesc("Fixing workbench-based reports..."); String usql = "ALTER TABLE " + databaseName + ".spreport CHANGE COLUMN SpQueryID SpQueryID INT(11) NULL"; if (update(conn, usql) == -1) { errMsgList.add("update error: " + usql); return false; } } frame.incOverall(); //------------------------------------------------------------------- // loan -- bug #9492. //------------------------------------------------------------------- frame.setDesc("Stretching SrcGeography and SrcGeography fields for loans and gifts..."); alterFieldLength(conn, databaseName, "loan", "SrcGeography", 32, 500); alterFieldLength(conn, databaseName, "loan", "SrcTaxonomy", 32, 500); //------------------------------------------------------------------- // gift -- bug #9492. //------------------------------------------------------------------- alterFieldLength(conn, databaseName, "gift", "SrcGeography", 32, 500); alterFieldLength(conn, databaseName, "gift", "SrcTaxonomy", 32, 500); frame.incOverall(); //------------------------------------------------------------------- //-- Change long strings that were created as text in earlier dbs and //-- as varchar in newer versions. // //-- bug #9457. //------------------------------------------------------------------- String[][] toFix = { { "accession", "Text1,Text2,Text3" }, { "borrow", "Text1,Text2" }, { "collectionobject", "Text1,Text2" }, { "collectionobjectattribute", "Text1,Text2,Text3" }, { "collectingeventattribute", "Text1,Text2,Text3" }, { "commonnametxcitation", "Text1,Text2" }, { "deaccession", "Text1,Text2" }, { "determination", "Text1,Text2" }, { "dnasequencingruncitation", "Text1,Text2" }, { "exchangein", "Text1,Text2" }, { "exchangeout", "Text1,Text2" }, { "gift", "Text1,Text2" }, { "lithostrat", "Text1,Text2" }, { "loan", "Text1,Text2" }, { "locality", "Text1,Text2" }, { "localitydetail", "Text1,Text2" }, { "permit", "Text1,Text2" }, { "preparation", "Text1,Text2" }, { "preparationattribute", "Text1,Text2,Text10" }, { "project", "Text1,Text2" }, { "referencework", "Text1,Text2" }, { "shipment", "Text1,Text2" }, { "taxoncitation", "Text1,Text2" }, { "workbenchdataitem", "CellData" } }; for (String[] fldToFix : toFix) { String tbl = fldToFix[0]; frame.setDesc("Fixing " + tbl + " user-defined Text field types..."); String[] flds = fldToFix[1].split(","); List<String> fldsToFix = new ArrayList<String>(flds.length); for (String fld : flds) { if (!"text".equals(getFieldColumnType(conn, databaseName, tbl, fld))) { fldsToFix.add(fld); } } String fldFixSql = "alter table " + databaseName + "." + tbl; boolean comma = false; for (String fld : fldsToFix) { if (comma) { fldFixSql += ","; } else { comma = true; } fldFixSql += " change column " + fld + " " + fld + " text"; } if (update(conn, fldFixSql) == -1) { errMsgList.add("update error: " + fldFixSql); return false; } } frame.incOverall(); //------------------------------------------------------------------ // Stretch ReferenceWork.Title and ReferenceWork.Publisher. #9718 //alterFieldLength(conn, databaseName, "referencework", "Title", 255, 255); alterFieldLength(conn, databaseName, "referencework", "Publisher", 50, 250); //------------------------------------------------------------------- // Create tables need for Geography Cleanup tool // geonames tables //------------------------------------------------------------------- //addGeoCleanupTables(); //frame.incOverall(); //------------------------------------------------------------------- //-- Create tables needed for iPad Export //------------------------------------------------------------------- addIPadExporterTables(conn); frame.incOverall(); //------------------------------------------------------------------- // Fixing unique constraint on author //-- bug #9454. //------------------------------------------------------------------- if (doesConstraintExist(conn, databaseName, "author", "OrderNumber")) { sql = "ALTER TABLE " + databaseName + ".author " + "DROP INDEX OrderNumber " + ", ADD UNIQUE INDEX AgentIDX (ReferenceWorkID ASC, AgentID ASC)"; frame.setDesc("Fixing ReferenceWork Author index..."); if (update(conn, sql) == -1) { errMsgList.add("update error: " + sql); return false; } } frame.incOverall(); //------------------------------------------------------------ // Matching CollectionMemberIDs between preparation and collectionobject // --bug #9760 fixPreparationCollectionMemberID(); frame.incOverall(); //------------------------------------------------------------------- // Ordinal in AttachmentObject tables made non-nullable //-- bug #9423. //------------------------------------------------------------------- String[] attObjTbls = { "accessionattachment", "agentattachment", "borrowattachment", "collectingeventattachment", "collectionobjectattachment", "conservdescriptionattachment", "conserveventattachment", "dnasequenceattachment", "dnasequencerunattachment", "fieldnotebookattachment", "fieldnotebookpageattachment", "fieldnotebookpagesetattachment", "giftattachment", "loanattachment", "localityattachment", "permitattachment", "preparationattachment", "referenceworkattachment", "repositoryagreementattachment", "taxonattachment" }; for (String tbl : attObjTbls) { if (getFieldNullability(conn, databaseName, tbl, "Ordinal")) { frame.setDesc("Fixing " + tbl + " Ordinal field requirement setting..."); String objTbl = tbl.replace("attachment", ""); String objTblKey = "dnasequencerun".equals(objTbl) ? "dnasequencingrunid" : objTbl + "ID"; String attObjTblKey = "dnasequencerun".equals(objTbl) ? "dnasequencingrunattachmentid" : tbl + "ID"; String q = "select " + objTblKey + ", " + attObjTblKey + " from " + databaseName + "." + tbl + " where Ordinal is null"; List<Object[]> nulls = BasicSQLUtils.query(conn, q); if (nulls != null && nulls.size() > 0) { for (Object[] row : nulls) { q = "select max(Ordinal) from " + databaseName + "." + tbl + " where " + objTblKey + "=" + row[0].toString(); Integer max = BasicSQLUtils.getCount(conn, q); if (max == null) { max = -1; } max += 1; q = "update " + databaseName + "." + tbl + " set Ordinal=" + max + " where " + attObjTblKey + "=" + row[1].toString(); if (-1 == update(conn, q)) { errMsgList.add("update error: " + q); return false; } } } q = "ALTER TABLE " + databaseName + "." + tbl + " CHANGE COLUMN `Ordinal` `Ordinal` INT(11) NOT NULL"; if (-1 == update(conn, q)) { errMsgList.add("update error: " + q); return false; } } } frame.incOverall(); //----------------------------------------------------------------------- // // Schema changes for 2.1 // //-------------------------------------------------------------------------- //change geocoord field types and values in export cache tables sql = "select SpExportSchemaMappingID, MappingName from spexportschemamapping"; List<Object[]> mappings = BasicSQLUtils.query(conn, sql); for (Object[] mapping : mappings) { frame.setDesc("Fixing geocoordinate precision for '" + mapping[1] + "' mapping..."); boolean updateOK = false; try { updateOK = ExportToMySQLDB.updateLatLngInCache(conn, (Integer) mapping[0]); } catch (Exception ex) { log.error(ex); } if (!updateOK) { log.error("Unable to fix geocoords for " + mapping[1] + ". Setting LastExportTime to null to force cache rebuild."); BasicSQLUtils.update(conn, "update spexportschemamapping set TimestampExported=null where spexportschemamappingid=" + mapping[0]); } } frame.incOverall(); //----------------------------------------------------------------------- // // Schema changes for 2.2 // //-------------------------------------------------------------------------- //change preparationattribute.attrdate from timestamp to date frame.setDesc("Fixing data type for preparationattribute.AttrDate"); sql = "alter table preparationattribute modify column attrdate date null"; if (-1 == update(conn, sql)) { errMsgList.add("update error: " + sql); return false; } frame.incOverall(); //add attachment.IsPublic, with default value = true frame.setDesc("Adding attachment.IsPublic field"); if (!doesColumnExist(databaseName, "attachment", "isPublic", conn)) { sql = "alter table attachment add column IsPublic bit(1) NOT NULL DEFAULT TRUE"; if (-1 == update(conn, sql)) { errMsgList.add("update error: " + sql); return false; } } frame.incOverall(); frame.setDesc("Fixing data type for localitydetail.Start/EndDepthUnit"); sql = "alter table localitydetail modify column enddepthunit varchar(23), modify column startdepthunit varchar(23)"; if (-1 == update(conn, sql)) { errMsgList.add("update error: " + sql); return false; } frame.setProcess(0, 100); frame.incOverall(); return true; } catch (Exception ex) { ex.printStackTrace(); } finally { if (stmt != null) { stmt.close(); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { if (dbConn != null) dbConn.close(); } return false; }
From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8TableFloatTable.java
protected MSSBamTableFloatBuff unpackTableFloatResultSetToBuff(ResultSet resultSet) throws SQLException { final String S_ProcName = "unpackTableFloatResultSetToBuff"; int idxcol = 1; String classCode = resultSet.getString(idxcol); idxcol++;// w w w. j av a2s . co m MSSBamTableFloatBuff buff; if (classCode.equals("TFLT")) { buff = schema.getFactoryTableFloat().newBuff(); } else { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Unrecognized class code \"" + classCode + "\""); } buff.setRequiredId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredTenantId(resultSet.getLong(idxcol)); idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalScopeId(null); } else { buff.setOptionalScopeId(colVal); } } idxcol++; buff.setRequiredName(resultSet.getString(idxcol)); idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortName(null); } else { buff.setOptionalShortName(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalLabel(null); } else { buff.setOptionalLabel(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortDescription(null); } else { buff.setOptionalShortDescription(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDescription(null); } else { buff.setOptionalDescription(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalAuthorId(null); } else { buff.setOptionalAuthorId(colVal); } } idxcol++; buff.setRequiredValueContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredIsNullable(resultSet.getBoolean(idxcol)); idxcol++; { boolean colVal = resultSet.getBoolean(idxcol); if (resultSet.wasNull()) { buff.setOptionalGenerateId(null); } else { buff.setOptionalGenerateId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalDataScopeId(null); } else { buff.setOptionalDataScopeId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessSecurityId(null); } else { buff.setOptionalViewAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessSecurityId(null); } else { buff.setOptionalEditAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessFrequencyId(null); } else { buff.setOptionalViewAccessFrequencyId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessFrequencyId(null); } else { buff.setOptionalEditAccessFrequencyId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalPrevId(null); } else { buff.setOptionalPrevId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalNextId(null); } else { buff.setOptionalNextId(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDbName(null); } else { buff.setOptionalDbName(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalInitValue(null); } else { buff.setOptionalInitValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalDefaultValue(null); } else { buff.setOptionalDefaultValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalMinValue(null); } else { buff.setOptionalMinValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalMaxValue(null); } else { buff.setOptionalMaxValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalNullValue(null); } else { buff.setOptionalNullValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalUnknownValue(null); } else { buff.setOptionalUnknownValue(colVal); } } idxcol++; buff.setRequiredContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredRevision(resultSet.getInt(idxcol)); return (buff); }
From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8SchemaFloatTable.java
protected MSSBamSchemaFloatBuff unpackSchemaFloatResultSetToBuff(ResultSet resultSet) throws SQLException { final String S_ProcName = "unpackSchemaFloatResultSetToBuff"; int idxcol = 1; String classCode = resultSet.getString(idxcol); idxcol++;/* w ww .j a v a 2 s . c om*/ MSSBamSchemaFloatBuff buff; if (classCode.equals("SFLT")) { buff = schema.getFactorySchemaFloat().newBuff(); } else { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Unrecognized class code \"" + classCode + "\""); } buff.setRequiredId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredTenantId(resultSet.getLong(idxcol)); idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalScopeId(null); } else { buff.setOptionalScopeId(colVal); } } idxcol++; buff.setRequiredName(resultSet.getString(idxcol)); idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortName(null); } else { buff.setOptionalShortName(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalLabel(null); } else { buff.setOptionalLabel(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortDescription(null); } else { buff.setOptionalShortDescription(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDescription(null); } else { buff.setOptionalDescription(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalAuthorId(null); } else { buff.setOptionalAuthorId(colVal); } } idxcol++; buff.setRequiredValueContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredIsNullable(resultSet.getBoolean(idxcol)); idxcol++; { boolean colVal = resultSet.getBoolean(idxcol); if (resultSet.wasNull()) { buff.setOptionalGenerateId(null); } else { buff.setOptionalGenerateId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalDataScopeId(null); } else { buff.setOptionalDataScopeId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessSecurityId(null); } else { buff.setOptionalViewAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessSecurityId(null); } else { buff.setOptionalEditAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessFrequencyId(null); } else { buff.setOptionalViewAccessFrequencyId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessFrequencyId(null); } else { buff.setOptionalEditAccessFrequencyId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalPrevId(null); } else { buff.setOptionalPrevId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalNextId(null); } else { buff.setOptionalNextId(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDbName(null); } else { buff.setOptionalDbName(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalInitValue(null); } else { buff.setOptionalInitValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalDefaultValue(null); } else { buff.setOptionalDefaultValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalMinValue(null); } else { buff.setOptionalMinValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalMaxValue(null); } else { buff.setOptionalMaxValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalNullValue(null); } else { buff.setOptionalNullValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalUnknownValue(null); } else { buff.setOptionalUnknownValue(colVal); } } idxcol++; buff.setRequiredContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredRevision(resultSet.getInt(idxcol)); return (buff); }
From source file:com.mycompany.demos.Servlet3b.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .jav a2s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; final String DB_URL = "jdbc:mysql://localhost:3306/garbagecollectionv2"; final String USER = "root"; final String PASS = "1234"; double existingLocationLat = 0, existingLocationLng = 0; int existingLocationId, newLocationId; //float fullness = 0; //System.out.println(request.getParameter("action")); Connection conn = null; Statement stmt = null; Statement stmt2 = null; try { //STEP 2: Register JDBC driver System.out.println("Loading Driver..."); Class.forName(JDBC_DRIVER); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); stmt2 = conn.createStatement(); String sql; if (request.getParameter("action").equals("add")) { sql = "insert into locations (lat,lng) values (" + request.getParameter("lat") + "," + request.getParameter("lng") + ");"; //System.out.println(sql); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs2 = stmt.getGeneratedKeys(); rs2.next(); newLocationId = rs2.getInt(1); rs2.close(); //System.out.println(newBinId); GraphHopper graphHopper = new GraphHopper() .setGraphHopperLocation("C:\\Users\\panikas\\Desktop\\diploma") // "gh-car" .setEncodingManager(new EncodingManager("car")) // "car" .setOSMFile("europe_germany_berlin.osm") // "germany-lastest.osm.pbf" .forServer(); graphHopper.importOrLoad(); GHRequest Grequest = null; GHResponse route = null; sql = "SELECT * FROM locations WHERE locationId != " + newLocationId + ";"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { existingLocationLat = rs.getDouble("lat"); existingLocationLng = rs.getDouble("lng"); existingLocationId = rs.getInt("locationId"); Grequest = new GHRequest(existingLocationLat, existingLocationLng, Double.parseDouble(request.getParameter("lat")), Double.parseDouble(request.getParameter("lng"))); Grequest.setWeighting("fastest"); Grequest.setVehicle("car"); route = graphHopper.route(Grequest); try (PrintWriter out = new PrintWriter( "C:\\Users\\panikas\\Desktop\\diploma\\code\\Demos\\target\\Demos-1.0-SNAPSHOT\\locations\\route" + existingLocationId + "_" + newLocationId + ".gpx")) { out.print(route.getBest().getInstructions().createGPX("Graphhopper", new Date().getTime(), false, false, true, false)); } catch (FileNotFoundException ex) { System.out.println("exception filenotfound"); } sql = "insert into distances (originId,destinationId,distance) values (" + existingLocationId + "," + newLocationId + "," + route.getBest().getTime() + ");"; stmt2.executeUpdate(sql); Grequest = new GHRequest(Double.parseDouble(request.getParameter("lat")), Double.parseDouble(request.getParameter("lng")), existingLocationLat, existingLocationLng); Grequest.setWeighting("fastest"); Grequest.setVehicle("car"); route = graphHopper.route(Grequest); try (PrintWriter out = new PrintWriter( "C:\\Users\\panikas\\Desktop\\diploma\\code\\Demos\\target\\Demos-1.0-SNAPSHOT\\locations\\route" + newLocationId + "_" + existingLocationId + ".gpx")) { out.print(route.getBest().getInstructions().createGPX("Graphhopper", new Date().getTime(), false, false, true, false)); } catch (FileNotFoundException ex) { System.out.println("exception filenotfound"); } sql = "insert into distances (originId,destinationId,distance) values (" + newLocationId + "," + existingLocationId + "," + route.getBest().getTime() + ");"; stmt2.executeUpdate(sql); } if (request.getParameter("type").equals("bin")) { sql = "insert into bins (locationId,fullness) values (" + newLocationId + "," + request.getParameter("fullness") + ");"; stmt.executeUpdate(sql); } else if (request.getParameter("type").equals("depot")) { sql = "insert into depots (locationId,numOfVehicles) values (" + newLocationId + "," + request.getParameter("numOfVehicles") + ");"; stmt.executeUpdate(sql); } rs.close(); } else if (request.getParameter("action").equals("delete")) { //System.out.println(request.getParameter("id")); sql = "delete from locations where locationId=" + request.getParameter("locationId") + ";"; stmt.executeUpdate(sql); } else if (request.getParameter("action").equals("update")) { //System.out.println(request.getParameter("id")); //System.out.println(request.getParameter("fullness")); sql = "update bins set fullness=" + request.getParameter("fullness") + " where binId=" + request.getParameter("binId") + ";"; stmt.executeUpdate(sql); } else if (request.getParameter("action").equals("optimise")) { String[] colours = { "#3333ff", "#ff33cc", "#ff6600", "#cc6600", "#cccc00" }; Collection<Location> locations = new ArrayList<Location>(); //new problem builder VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE); //add vehicles sql = "SELECT * FROM depots;"; ResultSet rs = stmt.executeQuery(sql); VehicleType type = VehicleTypeImpl.Builder.newInstance("garbageCollector") .addCapacityDimension(0, 1000).build(); VehicleImpl vehicle; Location currentLocation; int locationId, numOfVehicles, depotId; while (rs.next()) { locationId = rs.getInt("locationId"); numOfVehicles = rs.getInt("numOfVehicles"); depotId = rs.getInt("depotId"); currentLocation = Location.newInstance(Integer.toString(locationId)); for (int i = 0; i < numOfVehicles; i++) { vehicle = VehicleImpl.Builder.newInstance(depotId + "_" + i) .setStartLocation(currentLocation).setType(type).setReturnToDepot(true).build(); vrpBuilder.addVehicle(vehicle); } locations.add(currentLocation); } sql = "SELECT * FROM bins where fullness > 50;"; rs = stmt.executeQuery(sql); Service currentService; float fullness; while (rs.next()) { locationId = rs.getInt("locationId"); fullness = rs.getFloat("fullness"); currentLocation = Location.newInstance(Integer.toString(locationId)); currentService = Service.Builder.newInstance("service" + Integer.toString(locationId)) .addSizeDimension(0, (int) fullness).setLocation(currentLocation).build(); vrpBuilder.addJob(currentService); locations.add(currentLocation); } //distance matrix VehicleRoutingTransportCostsMatrix.Builder costMatrixBuilder = VehicleRoutingTransportCostsMatrix.Builder .newInstance(false); float distance; for (Location origin : locations) { //System.out.println(location.getId()); costMatrixBuilder.addTransportDistance(origin.getId(), origin.getId(), 0); for (Location destination : locations) { //System.out.println(origin.getId()); // System.out.println(destination.getId()); if (origin.getId() != destination.getId()) { sql = "SELECT distance FROM distances where originId = " + origin.getId() + " and destinationId = " + destination.getId() + ";"; rs = stmt.executeQuery(sql); rs.next(); distance = rs.getFloat("distance"); costMatrixBuilder.addTransportDistance(origin.getId(), destination.getId(), distance); } } } VehicleRoutingTransportCosts costMatrix = costMatrixBuilder.build(); vrpBuilder.setRoutingCost(costMatrix); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = Jsprit.createAlgorithm(vrp); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); SolutionPrinter.print(vrp, Solutions.bestOf(solutions), SolutionPrinter.Print.VERBOSE); //System.out.println("optimise"); JSONArray files, routes; JSONObject route, bins, bin, solution; routes = new JSONArray(); bins = new JSONObject(); solution = new JSONObject(); int routeCounter = 0; int position; for (VehicleRoute jroute : Solutions.bestOf(solutions).getRoutes()) { TourActivity prevAct = jroute.getStart(); route = new JSONObject(); files = new JSONArray(); position = 1; for (TourActivity act : jroute.getActivities()) { files.add("locations\\route" + prevAct.getLocation().getId() + "_" + act.getLocation().getId() + ".gpx"); bin = new JSONObject(); bin.put("colour", colours[routeCounter]); bin.put("position", position); bins.put(act.getLocation().getId(), bin); position++; prevAct = act; } files.add("locations\\route" + prevAct.getLocation().getId() + "_" + jroute.getEnd().getLocation().getId() + ".gpx"); route.put("files", files); route.put("colour", colours[routeCounter]); routes.add(route); routeCounter++; } solution.put("routes", routes); solution.put("bins", bins); System.out.println(solution.toString()); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(solution.toString()); } stmt.close(); stmt2.close(); conn.close(); } catch (SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException se2) { } try { if (stmt2 != null) { stmt2.close(); } } catch (SQLException se3) { } try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } } // JSONObject name = new JSONObject(); // JSONArray names = new JSONArray(); // // name.put( // "name", "foo1"); // name.put( // "surname", "bar1"); // // names.add(name); // name = new JSONObject(); // // name.put( // "name", "foo2"); // name.put( // "surname", "bar2"); //// names.add(name); // response.setContentType( // "application/json"); // response.setCharacterEncoding( // "UTF-8"); // response.getWriter() // .write(name.toString()); // System.out.println("done"); //System.out.println(names.toString()); //System.out.println(request.getParameter("action")); //System.out.println("blah"); }
From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8FloatDefTable.java
protected MSSBamFloatDefBuff unpackFloatDefResultSetToBuff(ResultSet resultSet) throws SQLException { final String S_ProcName = "unpackFloatDefResultSetToBuff"; int idxcol = 1; String classCode = resultSet.getString(idxcol); idxcol++;//from w w w . j a v a2s.co m MSSBamFloatDefBuff buff; if (classCode.equals("FLT")) { buff = schema.getFactoryFloatDef().newBuff(); } else if (classCode.equals("TFLT")) { buff = schema.getFactoryTableFloat().newBuff(); } else if (classCode.equals("SFLT")) { buff = schema.getFactorySchemaFloat().newBuff(); } else { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Unrecognized class code \"" + classCode + "\""); } buff.setRequiredId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredTenantId(resultSet.getLong(idxcol)); idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalScopeId(null); } else { buff.setOptionalScopeId(colVal); } } idxcol++; buff.setRequiredName(resultSet.getString(idxcol)); idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortName(null); } else { buff.setOptionalShortName(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalLabel(null); } else { buff.setOptionalLabel(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortDescription(null); } else { buff.setOptionalShortDescription(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDescription(null); } else { buff.setOptionalDescription(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalAuthorId(null); } else { buff.setOptionalAuthorId(colVal); } } idxcol++; buff.setRequiredValueContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredIsNullable(resultSet.getBoolean(idxcol)); idxcol++; { boolean colVal = resultSet.getBoolean(idxcol); if (resultSet.wasNull()) { buff.setOptionalGenerateId(null); } else { buff.setOptionalGenerateId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalDataScopeId(null); } else { buff.setOptionalDataScopeId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessSecurityId(null); } else { buff.setOptionalViewAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessSecurityId(null); } else { buff.setOptionalEditAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessFrequencyId(null); } else { buff.setOptionalViewAccessFrequencyId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessFrequencyId(null); } else { buff.setOptionalEditAccessFrequencyId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalPrevId(null); } else { buff.setOptionalPrevId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalNextId(null); } else { buff.setOptionalNextId(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDbName(null); } else { buff.setOptionalDbName(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalInitValue(null); } else { buff.setOptionalInitValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalDefaultValue(null); } else { buff.setOptionalDefaultValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalMinValue(null); } else { buff.setOptionalMinValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalMaxValue(null); } else { buff.setOptionalMaxValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalNullValue(null); } else { buff.setOptionalNullValue(colVal); } } idxcol++; { float colVal = resultSet.getFloat(idxcol); if (resultSet.wasNull()) { buff.setOptionalUnknownValue(null); } else { buff.setOptionalUnknownValue(colVal); } } idxcol++; buff.setRequiredRevision(resultSet.getInt(idxcol)); return (buff); }
From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java
/** * Load all detail entries for a content instance * * @param con open and valid(!) connection * @param conNoTX a non-transactional connection (only used if the content contains binary properties) * @param type FxType used/*from w w w . j av a 2s. c om*/ * @param env FxEnvironment * @param pk primary key of the content data to load * @param requestedVersion the originally requested version (LIVE, MAX or specific version number, needed to resolve references since the pk's version is resolved already) * @return a (root) group containing all data * @throws com.flexive.shared.exceptions.FxLoadException * on errors * @throws SQLException on errors * @throws FxInvalidParameterException on errors * @throws FxDbException on errors */ @SuppressWarnings("unchecked") protected FxGroupData loadDetails(Connection con, Connection conNoTX, FxType type, FxEnvironment env, FxPK pk, int requestedVersion, GroupPositionsProvider groupPositionsProvider) throws FxLoadException, SQLException, FxInvalidParameterException, FxDbException { FxGroupData root; PreparedStatement ps = null; try { root = type.createEmptyData(type.buildXPathPrefix(pk)); // root.removeEmptyEntries(true); // root.compactPositions(true); root.removeNonInternalData(); ps = con.prepareStatement(CONTENT_DATA_LOAD); ps.setLong(1, pk.getId()); ps.setInt(2, pk.getVersion()); ResultSet rs = ps.executeQuery(); String currXPath = null; int currXDepth = 0; FxAssignment currAssignment = null, thisAssignment = null; int currPos = -1; long currLang; long defLang = FxLanguage.SYSTEM_ID; boolean isGroup = true; boolean isMLDef; boolean multiLang = false; String currXMult; FxValue currValue = null; String[] columns = null; List<ServerLocation> server = CacheAdmin.getStreamServers(); //load flat columns FxFlatStorageLoadContainer flatContainer = type.isContainsFlatStorageAssignments() ? FxFlatStorageManager.getInstance().loadContent(this, con, type.getId(), pk, requestedVersion) : null; while (rs != null && rs.next()) { if (thisAssignment == null || thisAssignment.getId() != rs.getLong(3)) { //new data type thisAssignment = env.getAssignment(rs.getLong(3)); } currXMult = rs.getString(4); if (currXPath != null && !currXPath.equals(XPathElement.toXPathMult(thisAssignment.getXPath(), currXMult))) { //add this property if (!isGroup) { currValue.setDefaultLanguage(defLang); if (flatContainer != null) { //add flat entries that are positioned before the current entry FxFlatStorageLoadColumn flatColumn; while ((flatColumn = flatContainer.pop( currXPath.substring(0, currXPath.lastIndexOf('/') + 1), currXDepth, currPos)) != null) { addValue(root, flatColumn.getXPath(), flatColumn.getAssignment(), flatColumn.getPos(), groupPositionsProvider, flatColumn.getValue()); } } } addValue(root, currXPath, currAssignment, currPos, groupPositionsProvider, currValue); currValue = null; defLang = FxLanguage.SYSTEM_ID; } //read next row currPos = rs.getInt(1); currLang = rs.getInt(2); isMLDef = rs.getBoolean(6); isGroup = rs.getBoolean(5); if (currAssignment == null || currAssignment.getId() != thisAssignment.getId()) { currAssignment = thisAssignment; if (!isGroup) columns = getColumns(((FxPropertyAssignment) currAssignment).getProperty()); } currXPath = XPathElement.toXPathMult(currAssignment.getXPath(), currXMult); if (flatContainer != null) { //calculate xdepth currXDepth = 1; for (char c : currXMult.toCharArray()) if (c == ',') currXDepth++; } if (!isGroup) { final FxPropertyAssignment propAssignment = (FxPropertyAssignment) currAssignment; FxDataType dataType = propAssignment.getProperty().getDataType(); if (currValue == null) multiLang = propAssignment.isMultiLang(); switch (dataType) { case Float: if (currValue == null) currValue = new FxFloat(multiLang, currLang, rs.getFloat(columns[0])); else currValue.setTranslation(currLang, rs.getFloat(columns[0])); break; case Double: if (currValue == null) currValue = new FxDouble(multiLang, currLang, rs.getDouble(columns[0])); else currValue.setTranslation(currLang, rs.getDouble(columns[0])); break; case LargeNumber: if (currValue == null) currValue = new FxLargeNumber(multiLang, currLang, rs.getLong(columns[0])); else currValue.setTranslation(currLang, rs.getLong(columns[0])); break; case Number: if (currValue == null) currValue = new FxNumber(multiLang, currLang, rs.getInt(columns[0])); else currValue.setTranslation(currLang, rs.getInt(columns[0])); break; case HTML: if (currValue == null) { currValue = new FxHTML(multiLang, currLang, rs.getString(columns[0])); ((FxHTML) currValue).setTidyHTML(rs.getBoolean(columns[1])); } else currValue.setTranslation(currLang, rs.getString(columns[0])); break; case String1024: case Text: if (currValue == null) { currValue = new FxString(multiLang, currLang, rs.getString(columns[0])); } else currValue.setTranslation(currLang, rs.getString(columns[0])); break; case Boolean: if (currValue == null) currValue = new FxBoolean(multiLang, currLang, rs.getBoolean(columns[0])); else currValue.setTranslation(currLang, rs.getBoolean(columns[0])); break; case Date: if (currValue == null) currValue = new FxDate(multiLang, currLang, rs.getDate(columns[0])); else currValue.setTranslation(currLang, rs.getDate(columns[0])); break; case DateTime: if (currValue == null) currValue = new FxDateTime(multiLang, currLang, new Date(rs.getTimestamp(columns[0]).getTime())); else currValue.setTranslation(currLang, new Date(rs.getTimestamp(columns[0]).getTime())); break; case DateRange: if (currValue == null) currValue = new FxDateRange(multiLang, currLang, new DateRange(rs.getDate(columns[0]), rs.getDate( getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]))); else currValue.setTranslation(currLang, new DateRange(rs.getDate(columns[0]), rs.getDate( getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]))); break; case DateTimeRange: if (currValue == null) currValue = new FxDateTimeRange(multiLang, currLang, new DateRange( new Date(rs.getTimestamp(columns[0]).getTime()), new Date(rs.getTimestamp( getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]) .getTime()))); else currValue.setTranslation(currLang, new DateRange( new Date(rs.getTimestamp(columns[0]).getTime()), new Date(rs.getTimestamp( getColumns(((FxPropertyAssignment) currAssignment).getProperty())[1]) .getTime()))); break; case Binary: BinaryDescriptor desc = binaryStorage.loadBinaryDescriptor(server, conNoTX, rs.getLong(columns[0])); if (currValue == null) currValue = new FxBinary(multiLang, currLang, desc); else currValue.setTranslation(currLang, desc); break; case SelectOne: FxSelectListItem singleItem = env.getSelectListItem(rs.getLong(columns[0])); if (currValue == null) currValue = new FxSelectOne(multiLang, currLang, singleItem); else currValue.setTranslation(currLang, singleItem); break; case SelectMany: long itemId = rs.getLong(columns[0]); FxSelectList list = ((FxPropertyAssignment) currAssignment).getProperty() .getReferencedList(); if (currValue == null) currValue = new FxSelectMany(multiLang, currLang, new SelectMany(list)); FxSelectMany sm = (FxSelectMany) currValue; if (sm.isTranslationEmpty(currLang)) sm.setTranslation(currLang, new SelectMany(list)); if (itemId > 0) sm.getTranslation(currLang).selectItem(list.getItem(itemId)); break; case Reference: if (currValue == null) // currValue = new FxReference(multiLang, currLang, new ReferencedContent(rs.getLong(columns[0]))); currValue = new FxReference(multiLang, currLang, resolveReference(con, requestedVersion, rs.getLong(columns[0]))); else currValue.setTranslation(currLang, resolveReference(con, requestedVersion, rs.getLong(columns[0]))); break; default: throw new FxDbException(LOG, "ex.db.notImplemented.load", dataType.getName()); } if (currValue != null) { int valueData = rs.getInt(getValueDataLoadPos(dataType)); if (rs.wasNull()) currValue.clearValueData(currLang); else currValue.setValueData(currLang, valueData); } if (isMLDef) defLang = currLang; } } // check for empty groups for (Map.Entry<Long, Map<String, Integer>> entry : groupPositionsProvider.getPositions().entrySet()) { final long assignmentId = entry.getKey(); final FxGroupAssignment groupAssignment = (FxGroupAssignment) env.getAssignment(assignmentId); final Set<String> existingMults; final FxGroupData group = root.findGroup(assignmentId); if (group != null) { existingMults = Sets.newHashSet(); for (FxData data : group.getElements()) { existingMults.add(FxArrayUtils.toStringArray(data.getIndices(), ',')); } } else { existingMults = Collections.emptySet(); } for (Map.Entry<String, Integer> position : entry.getValue().entrySet()) { final String xmult = position.getKey(); if (!existingMults.contains(xmult) && groupAssignment.getMultiplicity().isRequired()) { // add (empty) group root.addGroup(XPathElement.toXPathMult(groupAssignment.getXPath(), xmult.replace('/', ',')), groupAssignment, position.getValue(), GROUPS_ONLY_SYS_INTERNAL); } } } if (currValue != null) { if (flatContainer != null) { //add flat entries that are positioned before the current entry FxFlatStorageLoadColumn flatColumn; while ((flatColumn = flatContainer.pop(currXPath.substring(0, currXPath.lastIndexOf('/') + 1), currXDepth, currPos)) != null) { addValue(root, flatColumn.getXPath(), flatColumn.getAssignment(), flatColumn.getPos(), groupPositionsProvider, flatColumn.getValue()); } } //add last property if (!isGroup) currValue.setDefaultLanguage(defLang); addValue(root, currXPath, currAssignment, currPos, groupPositionsProvider, currValue); } else { if (flatContainer == null && isGroup && currAssignment != null) //make sure to add the last assignment if it is a group and no flat storage is enabled addValue(root, currXPath, currAssignment, currPos, groupPositionsProvider, currValue); } if (flatContainer != null) { if (isGroup && currAssignment != null) //if the last value was a group, add it (can only happen when using a flat storage) addValue(root, currXPath, currAssignment, currPos, groupPositionsProvider, currValue); //add remaining flat entries FxFlatStorageLoadColumn flatColumn; while ((flatColumn = flatContainer.pop()) != null) { addValue(root, flatColumn.getXPath(), flatColumn.getAssignment(), flatColumn.getPos(), groupPositionsProvider, flatColumn.getValue()); } } // fix group positions after all groups have been added fixGroupPositions(root, groupPositionsProvider); } catch (FxCreateException e) { throw new FxLoadException(e); } catch (FxNotFoundException e) { throw new FxLoadException(e); } finally { Database.closeObjects(GenericHierarchicalStorage.class, ps); } return root; }
From source file:talonetl.getpropfinacials_0_1.getPropFinacials.java
public void tMysqlInput_1Process(final java.util.Map<String, Object> globalMap) throws TalendException { globalMap.put("tMysqlInput_1_SUBPROCESS_STATE", 0); final boolean execStat = this.execStat; String iterateId = ""; int iterateLoop = 0; String currentComponent = ""; try {//from w w w. ja v a 2s. c om String currentMethodName = new Exception().getStackTrace()[0].getMethodName(); boolean resumeIt = currentMethodName.equals(resumeEntryMethodName); if (resumeEntryMethodName == null || resumeIt || globalResumeTicket) {// start // the // resume globalResumeTicket = true; row11Struct row11 = new row11Struct(); /** * [tAdvancedHash_row11 begin ] start */ ok_Hash.put("tAdvancedHash_row11", false); start_Hash.put("tAdvancedHash_row11", System.currentTimeMillis()); currentComponent = "tAdvancedHash_row11"; int tos_count_tAdvancedHash_row11 = 0; // connection name:row11 // source node:tMysqlInput_1 - inputs:() outputs:(row11,row11) | // target node:tAdvancedHash_row11 - inputs:(row11) outputs:() // linked node: tMap_1 - inputs:(row1,row11) // outputs:(financed_net_yield_1__c,monthly_cash_flow_with_financing_2__c,financed_net_yield_2__c,monthly_cash_flow_with_financing_1__c,interest_rate_2__c) org.talend.designer.components.lookup.common.ICommonLookup.MATCHING_MODE matchingModeEnum_row11 = org.talend.designer.components.lookup.common.ICommonLookup.MATCHING_MODE.UNIQUE_MATCH; org.talend.designer.components.lookup.memory.AdvancedMemoryLookup<row11Struct> tHash_Lookup_row11 = org.talend.designer.components.lookup.memory.AdvancedMemoryLookup .<row11Struct>getLookup(matchingModeEnum_row11); globalMap.put("tHash_Lookup_row11", tHash_Lookup_row11); /** * [tAdvancedHash_row11 begin ] stop */ /** * [tMysqlInput_1 begin ] start */ ok_Hash.put("tMysqlInput_1", false); start_Hash.put("tMysqlInput_1", System.currentTimeMillis()); currentComponent = "tMysqlInput_1"; int tos_count_tMysqlInput_1 = 0; java.util.Calendar calendar_tMysqlInput_1 = java.util.Calendar.getInstance(); calendar_tMysqlInput_1.set(0, 0, 0, 0, 0, 0); java.util.Date year0_tMysqlInput_1 = calendar_tMysqlInput_1.getTime(); int nb_line_tMysqlInput_1 = 0; java.sql.Connection conn_tMysqlInput_1 = null; java.util.Map<String, routines.system.TalendDataSource> dataSources_tMysqlInput_1 = (java.util.Map<String, routines.system.TalendDataSource>) globalMap .get(KEY_DB_DATASOURCES); if (null != dataSources_tMysqlInput_1) { conn_tMysqlInput_1 = dataSources_tMysqlInput_1.get("").getConnection(); } else { java.lang.Class.forName("org.gjt.mm.mysql.Driver"); String url_tMysqlInput_1 = "jdbc:mysql://" + "192.168.1.254" + ":" + "3306" + "/" + "TALONDB" + "?" + "noDatetimeStringSync=true"; String dbUser_tMysqlInput_1 = "dbAdmin"; String dbPwd_tMysqlInput_1 = "1nn0s2013"; conn_tMysqlInput_1 = java.sql.DriverManager.getConnection(url_tMysqlInput_1, dbUser_tMysqlInput_1, dbPwd_tMysqlInput_1); } java.sql.Statement stmt_tMysqlInput_1 = conn_tMysqlInput_1.createStatement(); String dbquery_tMysqlInput_1 = "SELECT `PROPERTY_DATA`.`ID`, `PROPERTY_DATA`.`UUID`, `PROPERTY_DATA`.`PROP_NAME`, `PROPERTY_DATA`.`PRICE`, `PROPERTY_DATA`.`SQFT`, `PROPERTY_DATA`.`DESCRIPTION`, `PROPERTY_DATA`.`NUM_BEDS`, `PROPERTY_DATA`.`NUM_BATHS`, `PROPERTY_DATA`.`TYPE`, `PROPERTY_DATA`.`STATUS`, `PROPERTY_DATA`.`STATE_INFO_ID`, `PROPERTY_DATA`.`DATA_SOURCE_ID` FROM `PROPERTY_DATA`"; globalMap.put("tMysqlInput_1_QUERY", dbquery_tMysqlInput_1); java.sql.ResultSet rs_tMysqlInput_1 = stmt_tMysqlInput_1.executeQuery(dbquery_tMysqlInput_1); java.sql.ResultSetMetaData rsmd_tMysqlInput_1 = rs_tMysqlInput_1.getMetaData(); int colQtyInRs_tMysqlInput_1 = rsmd_tMysqlInput_1.getColumnCount(); String tmpContent_tMysqlInput_1 = null; while (rs_tMysqlInput_1.next()) { nb_line_tMysqlInput_1++; if (colQtyInRs_tMysqlInput_1 < 1) { row11.ID = 0; } else { if (rs_tMysqlInput_1.getObject(1) != null) { row11.ID = rs_tMysqlInput_1.getInt(1); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_1 < 2) { row11.UUID = null; } else { tmpContent_tMysqlInput_1 = rs_tMysqlInput_1.getString(2); if (tmpContent_tMysqlInput_1 != null) { row11.UUID = tmpContent_tMysqlInput_1; } else { row11.UUID = null; } } if (colQtyInRs_tMysqlInput_1 < 3) { row11.PROP_NAME = null; } else { tmpContent_tMysqlInput_1 = rs_tMysqlInput_1.getString(3); if (tmpContent_tMysqlInput_1 != null) { row11.PROP_NAME = tmpContent_tMysqlInput_1; } else { row11.PROP_NAME = null; } } if (colQtyInRs_tMysqlInput_1 < 4) { row11.PRICE = 0; } else { if (rs_tMysqlInput_1.getObject(4) != null) { row11.PRICE = rs_tMysqlInput_1.getFloat(4); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_1 < 5) { row11.SQFT = null; } else { tmpContent_tMysqlInput_1 = rs_tMysqlInput_1.getString(5); if (tmpContent_tMysqlInput_1 != null) { row11.SQFT = tmpContent_tMysqlInput_1; } else { row11.SQFT = null; } } if (colQtyInRs_tMysqlInput_1 < 6) { row11.DESCRIPTION = null; } else { tmpContent_tMysqlInput_1 = rs_tMysqlInput_1.getString(6); if (tmpContent_tMysqlInput_1 != null) { row11.DESCRIPTION = tmpContent_tMysqlInput_1; } else { row11.DESCRIPTION = null; } } if (colQtyInRs_tMysqlInput_1 < 7) { row11.NUM_BEDS = 0; } else { if (rs_tMysqlInput_1.getObject(7) != null) { row11.NUM_BEDS = rs_tMysqlInput_1.getFloat(7); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_1 < 8) { row11.NUM_BATHS = 0; } else { if (rs_tMysqlInput_1.getObject(8) != null) { row11.NUM_BATHS = rs_tMysqlInput_1.getFloat(8); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_1 < 9) { row11.TYPE = null; } else { tmpContent_tMysqlInput_1 = rs_tMysqlInput_1.getString(9); if (tmpContent_tMysqlInput_1 != null) { row11.TYPE = tmpContent_tMysqlInput_1; } else { row11.TYPE = null; } } if (colQtyInRs_tMysqlInput_1 < 10) { row11.STATUS = null; } else { tmpContent_tMysqlInput_1 = rs_tMysqlInput_1.getString(10); if (tmpContent_tMysqlInput_1 != null) { row11.STATUS = tmpContent_tMysqlInput_1; } else { row11.STATUS = null; } } if (colQtyInRs_tMysqlInput_1 < 11) { row11.STATE_INFO_ID = 0; } else { if (rs_tMysqlInput_1.getObject(11) != null) { row11.STATE_INFO_ID = rs_tMysqlInput_1.getInt(11); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_1 < 12) { row11.DATA_SOURCE_ID = 0; } else { if (rs_tMysqlInput_1.getObject(12) != null) { row11.DATA_SOURCE_ID = rs_tMysqlInput_1.getInt(12); } else { throw new RuntimeException("Null value in non-Nullable column"); } } /** * [tMysqlInput_1 begin ] stop */ /** * [tMysqlInput_1 main ] start */ currentComponent = "tMysqlInput_1"; tos_count_tMysqlInput_1++; /** * [tMysqlInput_1 main ] stop */ /** * [tAdvancedHash_row11 main ] start */ currentComponent = "tAdvancedHash_row11"; row11Struct row11_HashRow = new row11Struct(); row11_HashRow.ID = row11.ID; row11_HashRow.UUID = row11.UUID; row11_HashRow.PROP_NAME = row11.PROP_NAME; row11_HashRow.PRICE = row11.PRICE; row11_HashRow.SQFT = row11.SQFT; row11_HashRow.DESCRIPTION = row11.DESCRIPTION; row11_HashRow.NUM_BEDS = row11.NUM_BEDS; row11_HashRow.NUM_BATHS = row11.NUM_BATHS; row11_HashRow.TYPE = row11.TYPE; row11_HashRow.STATUS = row11.STATUS; row11_HashRow.STATE_INFO_ID = row11.STATE_INFO_ID; row11_HashRow.DATA_SOURCE_ID = row11.DATA_SOURCE_ID; tHash_Lookup_row11.put(row11_HashRow); tos_count_tAdvancedHash_row11++; /** * [tAdvancedHash_row11 main ] stop */ /** * [tMysqlInput_1 end ] start */ currentComponent = "tMysqlInput_1"; } rs_tMysqlInput_1.close(); stmt_tMysqlInput_1.close(); conn_tMysqlInput_1.close(); globalMap.put("tMysqlInput_1_NB_LINE", nb_line_tMysqlInput_1); ok_Hash.put("tMysqlInput_1", true); end_Hash.put("tMysqlInput_1", System.currentTimeMillis()); /** * [tMysqlInput_1 end ] stop */ /** * [tAdvancedHash_row11 end ] start */ currentComponent = "tAdvancedHash_row11"; tHash_Lookup_row11.endPut(); ok_Hash.put("tAdvancedHash_row11", true); end_Hash.put("tAdvancedHash_row11", System.currentTimeMillis()); /** * [tAdvancedHash_row11 end ] stop */ } // end the resume } catch (Exception e) { throw new TalendException(e, currentComponent, globalMap); } catch (java.lang.Error error) { throw new java.lang.Error(error); } globalMap.put("tMysqlInput_1_SUBPROCESS_STATE", 1); }
From source file:talonetl.loadpropertyimages_0_1.loadPropertyImages.java
public void tMysqlInput_2Process(final java.util.Map<String, Object> globalMap) throws TalendException { globalMap.put("tMysqlInput_2_SUBPROCESS_STATE", 0); final boolean execStat = this.execStat; String iterateId = ""; int iterateLoop = 0; String currentComponent = ""; try {// w w w . j av a2 s . com String currentMethodName = new Exception().getStackTrace()[0].getMethodName(); boolean resumeIt = currentMethodName.equals(resumeEntryMethodName); if (resumeEntryMethodName == null || resumeIt || globalResumeTicket) {// start // the // resume globalResumeTicket = true; row2Struct row2 = new row2Struct(); /** * [tAdvancedHash_row2 begin ] start */ ok_Hash.put("tAdvancedHash_row2", false); start_Hash.put("tAdvancedHash_row2", System.currentTimeMillis()); currentComponent = "tAdvancedHash_row2"; int tos_count_tAdvancedHash_row2 = 0; // connection name:row2 // source node:tMysqlInput_2 - inputs:(after_tFileInputXML_1) // outputs:(row2,row2) | target node:tAdvancedHash_row2 - // inputs:(row2) outputs:() // linked node: tMap_2 - inputs:(imageData,row2) // outputs:(loadImageData) org.talend.designer.components.lookup.common.ICommonLookup.MATCHING_MODE matchingModeEnum_row2 = org.talend.designer.components.lookup.common.ICommonLookup.MATCHING_MODE.UNIQUE_MATCH; org.talend.designer.components.lookup.memory.AdvancedMemoryLookup<row2Struct> tHash_Lookup_row2 = org.talend.designer.components.lookup.memory.AdvancedMemoryLookup .<row2Struct>getLookup(matchingModeEnum_row2); globalMap.put("tHash_Lookup_row2", tHash_Lookup_row2); /** * [tAdvancedHash_row2 begin ] stop */ /** * [tMysqlInput_2 begin ] start */ ok_Hash.put("tMysqlInput_2", false); start_Hash.put("tMysqlInput_2", System.currentTimeMillis()); currentComponent = "tMysqlInput_2"; int tos_count_tMysqlInput_2 = 0; java.util.Calendar calendar_tMysqlInput_2 = java.util.Calendar.getInstance(); calendar_tMysqlInput_2.set(0, 0, 0, 0, 0, 0); java.util.Date year0_tMysqlInput_2 = calendar_tMysqlInput_2.getTime(); int nb_line_tMysqlInput_2 = 0; java.sql.Connection conn_tMysqlInput_2 = null; java.util.Map<String, routines.system.TalendDataSource> dataSources_tMysqlInput_2 = (java.util.Map<String, routines.system.TalendDataSource>) globalMap .get(KEY_DB_DATASOURCES); if (null != dataSources_tMysqlInput_2) { conn_tMysqlInput_2 = dataSources_tMysqlInput_2.get("").getConnection(); } else { java.lang.Class.forName("org.gjt.mm.mysql.Driver"); String url_tMysqlInput_2 = "jdbc:mysql://" + "192.168.1.254" + ":" + "3306" + "/" + "TALONDB" + "?" + "noDatetimeStringSync=true"; String dbUser_tMysqlInput_2 = "dbAdmin"; String dbPwd_tMysqlInput_2 = "1nn0s2013"; conn_tMysqlInput_2 = java.sql.DriverManager.getConnection(url_tMysqlInput_2, dbUser_tMysqlInput_2, dbPwd_tMysqlInput_2); } java.sql.Statement stmt_tMysqlInput_2 = conn_tMysqlInput_2.createStatement(); String dbquery_tMysqlInput_2 = "SELECT `PROPERTY_DATA`.`ID`, `PROPERTY_DATA`.`UUID`, `PROPERTY_DATA`.`PROP_NAME`, `PROPERTY_DATA`.`PRICE`, `PROPERTY_DATA`.`SQFT`, `PROPERTY_DATA`.`DESCRIPTION`, `PROPERTY_DATA`.`NUM_BEDS`, `PROPERTY_DATA`.`NUM_BATHS`, `PROPERTY_DATA`.`TYPE`, `PROPERTY_DATA`.`STATUS`, `PROPERTY_DATA`.`STATE_INFO_ID`, `PROPERTY_DATA`.`DATA_SOURCE_ID` FROM `PROPERTY_DATA`"; globalMap.put("tMysqlInput_2_QUERY", dbquery_tMysqlInput_2); java.sql.ResultSet rs_tMysqlInput_2 = stmt_tMysqlInput_2.executeQuery(dbquery_tMysqlInput_2); java.sql.ResultSetMetaData rsmd_tMysqlInput_2 = rs_tMysqlInput_2.getMetaData(); int colQtyInRs_tMysqlInput_2 = rsmd_tMysqlInput_2.getColumnCount(); String tmpContent_tMysqlInput_2 = null; while (rs_tMysqlInput_2.next()) { nb_line_tMysqlInput_2++; if (colQtyInRs_tMysqlInput_2 < 1) { row2.ID = 0; } else { if (rs_tMysqlInput_2.getObject(1) != null) { row2.ID = rs_tMysqlInput_2.getInt(1); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_2 < 2) { row2.UUID = null; } else { tmpContent_tMysqlInput_2 = rs_tMysqlInput_2.getString(2); if (tmpContent_tMysqlInput_2 != null) { row2.UUID = tmpContent_tMysqlInput_2; } else { row2.UUID = null; } } if (colQtyInRs_tMysqlInput_2 < 3) { row2.PROP_NAME = null; } else { tmpContent_tMysqlInput_2 = rs_tMysqlInput_2.getString(3); if (tmpContent_tMysqlInput_2 != null) { row2.PROP_NAME = tmpContent_tMysqlInput_2; } else { row2.PROP_NAME = null; } } if (colQtyInRs_tMysqlInput_2 < 4) { row2.PRICE = 0; } else { if (rs_tMysqlInput_2.getObject(4) != null) { row2.PRICE = rs_tMysqlInput_2.getFloat(4); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_2 < 5) { row2.SQFT = null; } else { tmpContent_tMysqlInput_2 = rs_tMysqlInput_2.getString(5); if (tmpContent_tMysqlInput_2 != null) { row2.SQFT = tmpContent_tMysqlInput_2; } else { row2.SQFT = null; } } if (colQtyInRs_tMysqlInput_2 < 6) { row2.DESCRIPTION = null; } else { tmpContent_tMysqlInput_2 = rs_tMysqlInput_2.getString(6); if (tmpContent_tMysqlInput_2 != null) { row2.DESCRIPTION = tmpContent_tMysqlInput_2; } else { row2.DESCRIPTION = null; } } if (colQtyInRs_tMysqlInput_2 < 7) { row2.NUM_BEDS = 0; } else { if (rs_tMysqlInput_2.getObject(7) != null) { row2.NUM_BEDS = rs_tMysqlInput_2.getFloat(7); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_2 < 8) { row2.NUM_BATHS = 0; } else { if (rs_tMysqlInput_2.getObject(8) != null) { row2.NUM_BATHS = rs_tMysqlInput_2.getFloat(8); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_2 < 9) { row2.TYPE = null; } else { tmpContent_tMysqlInput_2 = rs_tMysqlInput_2.getString(9); if (tmpContent_tMysqlInput_2 != null) { row2.TYPE = tmpContent_tMysqlInput_2; } else { row2.TYPE = null; } } if (colQtyInRs_tMysqlInput_2 < 10) { row2.STATUS = null; } else { tmpContent_tMysqlInput_2 = rs_tMysqlInput_2.getString(10); if (tmpContent_tMysqlInput_2 != null) { row2.STATUS = tmpContent_tMysqlInput_2; } else { row2.STATUS = null; } } if (colQtyInRs_tMysqlInput_2 < 11) { row2.STATE_INFO_ID = 0; } else { if (rs_tMysqlInput_2.getObject(11) != null) { row2.STATE_INFO_ID = rs_tMysqlInput_2.getInt(11); } else { throw new RuntimeException("Null value in non-Nullable column"); } } if (colQtyInRs_tMysqlInput_2 < 12) { row2.DATA_SOURCE_ID = 0; } else { if (rs_tMysqlInput_2.getObject(12) != null) { row2.DATA_SOURCE_ID = rs_tMysqlInput_2.getInt(12); } else { throw new RuntimeException("Null value in non-Nullable column"); } } /** * [tMysqlInput_2 begin ] stop */ /** * [tMysqlInput_2 main ] start */ currentComponent = "tMysqlInput_2"; tos_count_tMysqlInput_2++; /** * [tMysqlInput_2 main ] stop */ /** * [tAdvancedHash_row2 main ] start */ currentComponent = "tAdvancedHash_row2"; row2Struct row2_HashRow = new row2Struct(); row2_HashRow.ID = row2.ID; row2_HashRow.UUID = row2.UUID; row2_HashRow.PROP_NAME = row2.PROP_NAME; row2_HashRow.PRICE = row2.PRICE; row2_HashRow.SQFT = row2.SQFT; row2_HashRow.DESCRIPTION = row2.DESCRIPTION; row2_HashRow.NUM_BEDS = row2.NUM_BEDS; row2_HashRow.NUM_BATHS = row2.NUM_BATHS; row2_HashRow.TYPE = row2.TYPE; row2_HashRow.STATUS = row2.STATUS; row2_HashRow.STATE_INFO_ID = row2.STATE_INFO_ID; row2_HashRow.DATA_SOURCE_ID = row2.DATA_SOURCE_ID; tHash_Lookup_row2.put(row2_HashRow); tos_count_tAdvancedHash_row2++; /** * [tAdvancedHash_row2 main ] stop */ /** * [tMysqlInput_2 end ] start */ currentComponent = "tMysqlInput_2"; } rs_tMysqlInput_2.close(); stmt_tMysqlInput_2.close(); conn_tMysqlInput_2.close(); globalMap.put("tMysqlInput_2_NB_LINE", nb_line_tMysqlInput_2); ok_Hash.put("tMysqlInput_2", true); end_Hash.put("tMysqlInput_2", System.currentTimeMillis()); /** * [tMysqlInput_2 end ] stop */ /** * [tAdvancedHash_row2 end ] start */ currentComponent = "tAdvancedHash_row2"; tHash_Lookup_row2.endPut(); ok_Hash.put("tAdvancedHash_row2", true); end_Hash.put("tAdvancedHash_row2", System.currentTimeMillis()); /** * [tAdvancedHash_row2 end ] stop */ } // end the resume } catch (Exception e) { throw new TalendException(e, currentComponent, globalMap); } catch (java.lang.Error error) { throw new java.lang.Error(error); } globalMap.put("tMysqlInput_2_SUBPROCESS_STATE", 1); }
From source file:edu.ku.brc.specify.conversion.GenericDBConversion.java
/** * Returns a converted value from the old schema to the new schema * @param rs the resultset// ww w . jav a 2s.c o m * @param index the index of the column in the resultset * @param type the defined type for the new schema * @param metaData the metat data describing the old schema column * @return the new data object */ protected Object getData(final ResultSet rs, final int index, final AttributeIFace.FieldType type, final FieldMetaData metaData) { // Note: we need to check the old schema once again because the "type" may have been mapped // so now we must map the actual value AttributeIFace.FieldType oldType = getDataType(metaData.getName(), metaData.getType()); try { Object value = rs.getObject(index); if (type == AttributeIFace.FieldType.BooleanType) { if (value == null) { return false; } else if (oldType == AttributeIFace.FieldType.IntegerType) { return rs.getInt(index) != 0; } else if (oldType == AttributeIFace.FieldType.FloatType) { return rs.getFloat(index) != 0.0f; } else if (oldType == AttributeIFace.FieldType.DoubleType) { return rs.getDouble(index) != 0.0; } else if (oldType == AttributeIFace.FieldType.StringType) { return rs.getString(index).equalsIgnoreCase("true"); } log.error("Error maping from schema[" + metaData.getType() + "] to [" + type.toString() + "]"); return false; } else if (type == AttributeIFace.FieldType.FloatType) { if (value == null) { return 0.0f; } else if (oldType == AttributeIFace.FieldType.FloatType) { return rs.getFloat(index); } else if (oldType == AttributeIFace.FieldType.DoubleType) { return rs.getFloat(index); } log.error("Error maping from schema[" + metaData.getType() + "] to [" + type.toString() + "]"); return 0.0f; } else if (type == AttributeIFace.FieldType.DoubleType) { if (value == null) { return 0.0; } else if (oldType == AttributeIFace.FieldType.FloatType) { return rs.getDouble(index); } else if (oldType == AttributeIFace.FieldType.DoubleType) { return rs.getDouble(index); } log.error("Error maping from schema[" + metaData.getType() + "] to [" + type.toString() + "]"); return 0.0; } else if (type == AttributeIFace.FieldType.IntegerType) { if (value == null) { return 0; } else if (oldType == AttributeIFace.FieldType.IntegerType) { return rs.getInt(index) != 0; } log.error("Error maping from schema[" + metaData.getType() + "] to [" + type.toString() + "]"); return 0; } else { return rs.getString(index); } } catch (SQLException ex) { log.error("Error maping from schema[" + metaData.getType() + "] to [" + type.toString() + "]"); log.error(ex); throw new RuntimeException(ex); } }