rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
dPrimeDisplay = new DPrimeDisplay(theData.dPrimeTable, infoKnown, theData.markerInfo); | dPrimeDisplay = new DPrimeDisplay(theData.dPrimeTable, infoKnown); | void drawPicture(HaploData theData){ Container contents = getContentPane(); contents.removeAll(); //remember which tab we're in if they've already been set up int currentTabIndex = 0; if (!(tabs == null)){ currentTabIndex = tabs.getSelectedIndex(); } tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(theData.dPrimeTable, infoKnown, theData.markerInfo); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[0], panel); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); hapDisplay = new HaplotypeDisplay(theData); HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); JScrollPane hapScroller = new JScrollPane(hapDisplay); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[1], panel); tabs.setSelectedIndex(currentTabIndex); contents.add(tabs); //next add a little spacer //ontents.add(Box.createRigidArea(new Dimension(0,5))); //and then add the block display //theBlocks = new BlockDisplay(theData.markerInfo, theData.blocks, dPrimeDisplay, infoKnown); //contents.setBackground(Color.black); //put the block display in a scroll pane in case the data set is very large. //JScrollPane blockScroller = new JScrollPane(theBlocks, // JScrollPane.VERTICAL_SCROLLBAR_NEVER, // JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); //blockScroller.getHorizontalScrollBar().setUnitIncrement(60); //blockScroller.setMinimumSize(new Dimension(800, 100)); //contents.add(blockScroller); repaint(); setVisible(true); } |
window = new HaploView(); window.argHandler(args); | public static void main(String[] args) {//throws IOException{ boolean nogui = false; HaploView window; for(int i = 0;i<args.length;i++) { if(args[i].equals("-nogui") || args[i].equals("-n") ) { nogui = true; } } if(nogui) { window = new HaploView(args); } else { window = new HaploView(); window.argHandler(args); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } //setup view object window.setTitle("HaploView beta"); window.setSize(800,600); //center the window on the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation((screen.width - window.getWidth()) / 2, (screen.height - window.getHeight()) / 2); window.setVisible(true); ReadDataDialog readDialog = new ReadDataDialog("Welcome to HaploView", window); readDialog.pack(); readDialog.setVisible(true); } } |
|
window = new HaploView(); window.argHandler(args); | public static void main(String[] args) {//throws IOException{ boolean nogui = false; HaploView window; for(int i = 0;i<args.length;i++) { if(args[i].equals("-nogui") || args[i].equals("-n") ) { nogui = true; } } if(nogui) { window = new HaploView(args); } else { window = new HaploView(); window.argHandler(args); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } //setup view object window.setTitle("HaploView beta"); window.setSize(800,600); //center the window on the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation((screen.width - window.getWidth()) / 2, (screen.height - window.getHeight()) / 2); window.setVisible(true); ReadDataDialog readDialog = new ReadDataDialog("Welcome to HaploView", window); readDialog.pack(); readDialog.setVisible(true); } } |
|
dPrimeDisplay.loadMarkers(theData.markerInfo); | dPrimeDisplay.loadMarkers(); | void readMarkers(File inputFile){ try { int good = theData.prepareMarkerInput(inputFile); if (good == -1){ JOptionPane.showMessageDialog(this, "Number of markers in info file does not match number of markers in dataset.", "Error", JOptionPane.ERROR_MESSAGE); }else{ infoKnown=true; if (dPrimeDisplay != null){ dPrimeDisplay.loadMarkers(theData.markerInfo); } } }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (RuntimeException rtexec){ JOptionPane.showMessageDialog(this, "An error has occured. It is probably related to file format:\n"+rtexec.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } |
new TextMethods().saveDprimeToText(theData.dPrimeTable, fc.getSelectedFile(), infoKnown, theData.markerInfo); | new TextMethods().saveDprimeToText(theData.dPrimeTable, fc.getSelectedFile(), infoKnown, new Vector()); | void saveDprimeToText(){ fc.setSelectedFile(null); try{ fc.setSelectedFile(null); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { new TextMethods().saveDprimeToText(theData.dPrimeTable, fc.getSelectedFile(), infoKnown, theData.markerInfo); } }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } } |
String databaseIdentifierQuoteString = null; | private void doColumnProfile(List<SQLColumn> columns, Connection conn) throws SQLException { Statement stmt = null; ResultSet rs = null; String lastSQL = null; try { if ( columns.size() == 0 ) return; SQLColumn col1 = columns.get(0); DDLGenerator ddlg = null; Class generatorClass = null; try { Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); generatorClass = (Class) ddlGeneratorMap.get( col1.getParentTable().getParentDatabase().getDataSource().getDriverClass()); // FIXME: make warning user visable if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } ddlg = (DDLGenerator) generatorClass.newInstance(); } catch (InstantiationException e1) { logger.error("problem running Profile Manager", e1); } catch ( IllegalAccessException e1 ) { logger.error("problem running Profile Manager", e1); } stmt = conn.createStatement(); stmt.setEscapeProcessing(false); int i = 0; for (SQLColumn col : columns ) { ProfileFunctionDescriptor pfd = ddlg.getProfileFunctionMap().get(col.getSourceDataTypeName()); ColumnProfileResult colResult = new ColumnProfileResult(System.currentTimeMillis()); if ( pfd == null ) { System.out.println(col.getName()+ " Unknown DataType:(" + col.getSourceDataTypeName() + "). please setup the profile function mapping"); continue; } StringBuffer sql = new StringBuffer(); sql.append("SELECT 1"); if (findingDistinctCount && pfd.isCountDist() ) { sql.append(",\n COUNT(DISTINCT \""); sql.append(col.getName()); sql.append("\") AS DISTINCTCOUNT_"+i); } if (findingMin && pfd.isMinValue() ) { sql.append(",\n MIN(\""); sql.append(col.getName()); sql.append("\") AS MINVALUE_"+i); } if (findingMax && pfd.isMaxValus() ) { sql.append(",\n MAX(\""); sql.append(col.getName()); sql.append("\") AS MAXVALUE_"+i); } if (findingAvg && pfd.isAvgValue() ) { sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); } if (findingMinLength && pfd.isMinLength() ) { sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); } if (findingMaxLength && pfd.isMaxLength() ) { sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); } if (findingAvgLength && pfd.isAvgLength() ) { sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); } if ( findingNullCount && pfd.isSumDecode() ) { sql.append(",\n SUM("); sql.append(ddlg.caseWhen("\""+col.getName()+"\"", "NULL", "1")); sql.append(") AS NULLCOUNT_"+i); } SQLTable table = col.getParentTable(); sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { if (findingDistinctCount && pfd.isCountDist() ) { lastSQL = "DISTINCTCOUNT_"+i; colResult.setDistinctValueCount(rs.getInt(lastSQL)); } if (findingMin && pfd.isMinValue() ) { lastSQL = "MINVALUE_"+i; colResult.setMinValue(rs.getObject(lastSQL)); } if (findingMax && pfd.isMaxValus() ) { lastSQL = "MAXVALUE_"+i; colResult.setMaxValue(rs.getObject(lastSQL)); } if (findingAvg && pfd.isAvgValue() ) { lastSQL = "AVGVALUE_"+i; colResult.setAvgValue(rs.getObject(lastSQL)); } if (findingMinLength && pfd.isMinLength() ) { lastSQL = "MINLENGTH_"+i; colResult.setMinLength(rs.getInt(lastSQL)); } if (findingMaxLength && pfd.isMaxLength() ) { lastSQL = "MAXLENGTH_"+i; colResult.setMaxLength(rs.getInt(lastSQL)); } if (findingAvgLength && pfd.isAvgLength() ) { lastSQL = "AVGLENGTH_"+i; colResult.setAvgLength(rs.getInt(lastSQL)); } if ( findingNullCount && pfd.isSumDecode() ) { lastSQL = "NULLCOUNT_"+i; colResult.setNullCount(rs.getInt(lastSQL)); } } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } i++; if (findingTopTen && pfd.isCountDist() ) { sql = new StringBuffer(); sql.append("SELECT \""); sql.append(col.getName()); sql.append("\" AS MYVALUE, COUNT(*) AS COUNT1 FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); sql.append(" GROUP BY \""); sql.append(col.getName()); sql.append("\" ORDER BY COUNT1 DESC"); colResult = (ColumnProfileResult) getResult(col); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); for ( int n=0; rs.next() && n < 10; n++ ) { colResult.addValueCount(rs.getObject("MYVALUE"), rs.getInt("COUNT1")); } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } } } // XXX: add where filter later } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } } } |
|
sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); | sql.append(",\n "); sql.append(ddlg.getAverageSQLFunctionName("\""+col.getName()+"\"")); sql.append(" AS AVGVALUE_"+i); | private void doColumnProfile(List<SQLColumn> columns, Connection conn) throws SQLException { Statement stmt = null; ResultSet rs = null; String lastSQL = null; try { if ( columns.size() == 0 ) return; SQLColumn col1 = columns.get(0); DDLGenerator ddlg = null; Class generatorClass = null; try { Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); generatorClass = (Class) ddlGeneratorMap.get( col1.getParentTable().getParentDatabase().getDataSource().getDriverClass()); // FIXME: make warning user visable if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } ddlg = (DDLGenerator) generatorClass.newInstance(); } catch (InstantiationException e1) { logger.error("problem running Profile Manager", e1); } catch ( IllegalAccessException e1 ) { logger.error("problem running Profile Manager", e1); } stmt = conn.createStatement(); stmt.setEscapeProcessing(false); int i = 0; for (SQLColumn col : columns ) { ProfileFunctionDescriptor pfd = ddlg.getProfileFunctionMap().get(col.getSourceDataTypeName()); ColumnProfileResult colResult = new ColumnProfileResult(System.currentTimeMillis()); if ( pfd == null ) { System.out.println(col.getName()+ " Unknown DataType:(" + col.getSourceDataTypeName() + "). please setup the profile function mapping"); continue; } StringBuffer sql = new StringBuffer(); sql.append("SELECT 1"); if (findingDistinctCount && pfd.isCountDist() ) { sql.append(",\n COUNT(DISTINCT \""); sql.append(col.getName()); sql.append("\") AS DISTINCTCOUNT_"+i); } if (findingMin && pfd.isMinValue() ) { sql.append(",\n MIN(\""); sql.append(col.getName()); sql.append("\") AS MINVALUE_"+i); } if (findingMax && pfd.isMaxValus() ) { sql.append(",\n MAX(\""); sql.append(col.getName()); sql.append("\") AS MAXVALUE_"+i); } if (findingAvg && pfd.isAvgValue() ) { sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); } if (findingMinLength && pfd.isMinLength() ) { sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); } if (findingMaxLength && pfd.isMaxLength() ) { sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); } if (findingAvgLength && pfd.isAvgLength() ) { sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); } if ( findingNullCount && pfd.isSumDecode() ) { sql.append(",\n SUM("); sql.append(ddlg.caseWhen("\""+col.getName()+"\"", "NULL", "1")); sql.append(") AS NULLCOUNT_"+i); } SQLTable table = col.getParentTable(); sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { if (findingDistinctCount && pfd.isCountDist() ) { lastSQL = "DISTINCTCOUNT_"+i; colResult.setDistinctValueCount(rs.getInt(lastSQL)); } if (findingMin && pfd.isMinValue() ) { lastSQL = "MINVALUE_"+i; colResult.setMinValue(rs.getObject(lastSQL)); } if (findingMax && pfd.isMaxValus() ) { lastSQL = "MAXVALUE_"+i; colResult.setMaxValue(rs.getObject(lastSQL)); } if (findingAvg && pfd.isAvgValue() ) { lastSQL = "AVGVALUE_"+i; colResult.setAvgValue(rs.getObject(lastSQL)); } if (findingMinLength && pfd.isMinLength() ) { lastSQL = "MINLENGTH_"+i; colResult.setMinLength(rs.getInt(lastSQL)); } if (findingMaxLength && pfd.isMaxLength() ) { lastSQL = "MAXLENGTH_"+i; colResult.setMaxLength(rs.getInt(lastSQL)); } if (findingAvgLength && pfd.isAvgLength() ) { lastSQL = "AVGLENGTH_"+i; colResult.setAvgLength(rs.getInt(lastSQL)); } if ( findingNullCount && pfd.isSumDecode() ) { lastSQL = "NULLCOUNT_"+i; colResult.setNullCount(rs.getInt(lastSQL)); } } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } i++; if (findingTopTen && pfd.isCountDist() ) { sql = new StringBuffer(); sql.append("SELECT \""); sql.append(col.getName()); sql.append("\" AS MYVALUE, COUNT(*) AS COUNT1 FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); sql.append(" GROUP BY \""); sql.append(col.getName()); sql.append("\" ORDER BY COUNT1 DESC"); colResult = (ColumnProfileResult) getResult(col); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); for ( int n=0; rs.next() && n < 10; n++ ) { colResult.addValueCount(rs.getObject("MYVALUE"), rs.getInt("COUNT1")); } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } } } // XXX: add where filter later } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } } } |
sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); | sql.append(",\n MIN("); sql.append(ddlg.getStringLengthSQLFunctionName("\""+col.getName()+"\"")); sql.append(") AS MINLENGTH_"+i); | private void doColumnProfile(List<SQLColumn> columns, Connection conn) throws SQLException { Statement stmt = null; ResultSet rs = null; String lastSQL = null; try { if ( columns.size() == 0 ) return; SQLColumn col1 = columns.get(0); DDLGenerator ddlg = null; Class generatorClass = null; try { Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); generatorClass = (Class) ddlGeneratorMap.get( col1.getParentTable().getParentDatabase().getDataSource().getDriverClass()); // FIXME: make warning user visable if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } ddlg = (DDLGenerator) generatorClass.newInstance(); } catch (InstantiationException e1) { logger.error("problem running Profile Manager", e1); } catch ( IllegalAccessException e1 ) { logger.error("problem running Profile Manager", e1); } stmt = conn.createStatement(); stmt.setEscapeProcessing(false); int i = 0; for (SQLColumn col : columns ) { ProfileFunctionDescriptor pfd = ddlg.getProfileFunctionMap().get(col.getSourceDataTypeName()); ColumnProfileResult colResult = new ColumnProfileResult(System.currentTimeMillis()); if ( pfd == null ) { System.out.println(col.getName()+ " Unknown DataType:(" + col.getSourceDataTypeName() + "). please setup the profile function mapping"); continue; } StringBuffer sql = new StringBuffer(); sql.append("SELECT 1"); if (findingDistinctCount && pfd.isCountDist() ) { sql.append(",\n COUNT(DISTINCT \""); sql.append(col.getName()); sql.append("\") AS DISTINCTCOUNT_"+i); } if (findingMin && pfd.isMinValue() ) { sql.append(",\n MIN(\""); sql.append(col.getName()); sql.append("\") AS MINVALUE_"+i); } if (findingMax && pfd.isMaxValus() ) { sql.append(",\n MAX(\""); sql.append(col.getName()); sql.append("\") AS MAXVALUE_"+i); } if (findingAvg && pfd.isAvgValue() ) { sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); } if (findingMinLength && pfd.isMinLength() ) { sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); } if (findingMaxLength && pfd.isMaxLength() ) { sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); } if (findingAvgLength && pfd.isAvgLength() ) { sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); } if ( findingNullCount && pfd.isSumDecode() ) { sql.append(",\n SUM("); sql.append(ddlg.caseWhen("\""+col.getName()+"\"", "NULL", "1")); sql.append(") AS NULLCOUNT_"+i); } SQLTable table = col.getParentTable(); sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { if (findingDistinctCount && pfd.isCountDist() ) { lastSQL = "DISTINCTCOUNT_"+i; colResult.setDistinctValueCount(rs.getInt(lastSQL)); } if (findingMin && pfd.isMinValue() ) { lastSQL = "MINVALUE_"+i; colResult.setMinValue(rs.getObject(lastSQL)); } if (findingMax && pfd.isMaxValus() ) { lastSQL = "MAXVALUE_"+i; colResult.setMaxValue(rs.getObject(lastSQL)); } if (findingAvg && pfd.isAvgValue() ) { lastSQL = "AVGVALUE_"+i; colResult.setAvgValue(rs.getObject(lastSQL)); } if (findingMinLength && pfd.isMinLength() ) { lastSQL = "MINLENGTH_"+i; colResult.setMinLength(rs.getInt(lastSQL)); } if (findingMaxLength && pfd.isMaxLength() ) { lastSQL = "MAXLENGTH_"+i; colResult.setMaxLength(rs.getInt(lastSQL)); } if (findingAvgLength && pfd.isAvgLength() ) { lastSQL = "AVGLENGTH_"+i; colResult.setAvgLength(rs.getInt(lastSQL)); } if ( findingNullCount && pfd.isSumDecode() ) { lastSQL = "NULLCOUNT_"+i; colResult.setNullCount(rs.getInt(lastSQL)); } } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } i++; if (findingTopTen && pfd.isCountDist() ) { sql = new StringBuffer(); sql.append("SELECT \""); sql.append(col.getName()); sql.append("\" AS MYVALUE, COUNT(*) AS COUNT1 FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); sql.append(" GROUP BY \""); sql.append(col.getName()); sql.append("\" ORDER BY COUNT1 DESC"); colResult = (ColumnProfileResult) getResult(col); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); for ( int n=0; rs.next() && n < 10; n++ ) { colResult.addValueCount(rs.getObject("MYVALUE"), rs.getInt("COUNT1")); } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } } } // XXX: add where filter later } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } } } |
sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); | sql.append(",\n MAX("); sql.append(ddlg.getStringLengthSQLFunctionName("\""+col.getName()+"\"")); sql.append(") AS MAXLENGTH_"+i); | private void doColumnProfile(List<SQLColumn> columns, Connection conn) throws SQLException { Statement stmt = null; ResultSet rs = null; String lastSQL = null; try { if ( columns.size() == 0 ) return; SQLColumn col1 = columns.get(0); DDLGenerator ddlg = null; Class generatorClass = null; try { Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); generatorClass = (Class) ddlGeneratorMap.get( col1.getParentTable().getParentDatabase().getDataSource().getDriverClass()); // FIXME: make warning user visable if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } ddlg = (DDLGenerator) generatorClass.newInstance(); } catch (InstantiationException e1) { logger.error("problem running Profile Manager", e1); } catch ( IllegalAccessException e1 ) { logger.error("problem running Profile Manager", e1); } stmt = conn.createStatement(); stmt.setEscapeProcessing(false); int i = 0; for (SQLColumn col : columns ) { ProfileFunctionDescriptor pfd = ddlg.getProfileFunctionMap().get(col.getSourceDataTypeName()); ColumnProfileResult colResult = new ColumnProfileResult(System.currentTimeMillis()); if ( pfd == null ) { System.out.println(col.getName()+ " Unknown DataType:(" + col.getSourceDataTypeName() + "). please setup the profile function mapping"); continue; } StringBuffer sql = new StringBuffer(); sql.append("SELECT 1"); if (findingDistinctCount && pfd.isCountDist() ) { sql.append(",\n COUNT(DISTINCT \""); sql.append(col.getName()); sql.append("\") AS DISTINCTCOUNT_"+i); } if (findingMin && pfd.isMinValue() ) { sql.append(",\n MIN(\""); sql.append(col.getName()); sql.append("\") AS MINVALUE_"+i); } if (findingMax && pfd.isMaxValus() ) { sql.append(",\n MAX(\""); sql.append(col.getName()); sql.append("\") AS MAXVALUE_"+i); } if (findingAvg && pfd.isAvgValue() ) { sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); } if (findingMinLength && pfd.isMinLength() ) { sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); } if (findingMaxLength && pfd.isMaxLength() ) { sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); } if (findingAvgLength && pfd.isAvgLength() ) { sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); } if ( findingNullCount && pfd.isSumDecode() ) { sql.append(",\n SUM("); sql.append(ddlg.caseWhen("\""+col.getName()+"\"", "NULL", "1")); sql.append(") AS NULLCOUNT_"+i); } SQLTable table = col.getParentTable(); sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { if (findingDistinctCount && pfd.isCountDist() ) { lastSQL = "DISTINCTCOUNT_"+i; colResult.setDistinctValueCount(rs.getInt(lastSQL)); } if (findingMin && pfd.isMinValue() ) { lastSQL = "MINVALUE_"+i; colResult.setMinValue(rs.getObject(lastSQL)); } if (findingMax && pfd.isMaxValus() ) { lastSQL = "MAXVALUE_"+i; colResult.setMaxValue(rs.getObject(lastSQL)); } if (findingAvg && pfd.isAvgValue() ) { lastSQL = "AVGVALUE_"+i; colResult.setAvgValue(rs.getObject(lastSQL)); } if (findingMinLength && pfd.isMinLength() ) { lastSQL = "MINLENGTH_"+i; colResult.setMinLength(rs.getInt(lastSQL)); } if (findingMaxLength && pfd.isMaxLength() ) { lastSQL = "MAXLENGTH_"+i; colResult.setMaxLength(rs.getInt(lastSQL)); } if (findingAvgLength && pfd.isAvgLength() ) { lastSQL = "AVGLENGTH_"+i; colResult.setAvgLength(rs.getInt(lastSQL)); } if ( findingNullCount && pfd.isSumDecode() ) { lastSQL = "NULLCOUNT_"+i; colResult.setNullCount(rs.getInt(lastSQL)); } } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } i++; if (findingTopTen && pfd.isCountDist() ) { sql = new StringBuffer(); sql.append("SELECT \""); sql.append(col.getName()); sql.append("\" AS MYVALUE, COUNT(*) AS COUNT1 FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); sql.append(" GROUP BY \""); sql.append(col.getName()); sql.append("\" ORDER BY COUNT1 DESC"); colResult = (ColumnProfileResult) getResult(col); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); for ( int n=0; rs.next() && n < 10; n++ ) { colResult.addValueCount(rs.getObject("MYVALUE"), rs.getInt("COUNT1")); } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } } } // XXX: add where filter later } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } } } |
sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); | sql.append(",\n AVG("); sql.append(ddlg.getStringLengthSQLFunctionName("\""+col.getName()+"\"")); sql.append(") AS AVGLENGTH_"+i); | private void doColumnProfile(List<SQLColumn> columns, Connection conn) throws SQLException { Statement stmt = null; ResultSet rs = null; String lastSQL = null; try { if ( columns.size() == 0 ) return; SQLColumn col1 = columns.get(0); DDLGenerator ddlg = null; Class generatorClass = null; try { Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); generatorClass = (Class) ddlGeneratorMap.get( col1.getParentTable().getParentDatabase().getDataSource().getDriverClass()); // FIXME: make warning user visable if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } ddlg = (DDLGenerator) generatorClass.newInstance(); } catch (InstantiationException e1) { logger.error("problem running Profile Manager", e1); } catch ( IllegalAccessException e1 ) { logger.error("problem running Profile Manager", e1); } stmt = conn.createStatement(); stmt.setEscapeProcessing(false); int i = 0; for (SQLColumn col : columns ) { ProfileFunctionDescriptor pfd = ddlg.getProfileFunctionMap().get(col.getSourceDataTypeName()); ColumnProfileResult colResult = new ColumnProfileResult(System.currentTimeMillis()); if ( pfd == null ) { System.out.println(col.getName()+ " Unknown DataType:(" + col.getSourceDataTypeName() + "). please setup the profile function mapping"); continue; } StringBuffer sql = new StringBuffer(); sql.append("SELECT 1"); if (findingDistinctCount && pfd.isCountDist() ) { sql.append(",\n COUNT(DISTINCT \""); sql.append(col.getName()); sql.append("\") AS DISTINCTCOUNT_"+i); } if (findingMin && pfd.isMinValue() ) { sql.append(",\n MIN(\""); sql.append(col.getName()); sql.append("\") AS MINVALUE_"+i); } if (findingMax && pfd.isMaxValus() ) { sql.append(",\n MAX(\""); sql.append(col.getName()); sql.append("\") AS MAXVALUE_"+i); } if (findingAvg && pfd.isAvgValue() ) { sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); } if (findingMinLength && pfd.isMinLength() ) { sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); } if (findingMaxLength && pfd.isMaxLength() ) { sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); } if (findingAvgLength && pfd.isAvgLength() ) { sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); } if ( findingNullCount && pfd.isSumDecode() ) { sql.append(",\n SUM("); sql.append(ddlg.caseWhen("\""+col.getName()+"\"", "NULL", "1")); sql.append(") AS NULLCOUNT_"+i); } SQLTable table = col.getParentTable(); sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { if (findingDistinctCount && pfd.isCountDist() ) { lastSQL = "DISTINCTCOUNT_"+i; colResult.setDistinctValueCount(rs.getInt(lastSQL)); } if (findingMin && pfd.isMinValue() ) { lastSQL = "MINVALUE_"+i; colResult.setMinValue(rs.getObject(lastSQL)); } if (findingMax && pfd.isMaxValus() ) { lastSQL = "MAXVALUE_"+i; colResult.setMaxValue(rs.getObject(lastSQL)); } if (findingAvg && pfd.isAvgValue() ) { lastSQL = "AVGVALUE_"+i; colResult.setAvgValue(rs.getObject(lastSQL)); } if (findingMinLength && pfd.isMinLength() ) { lastSQL = "MINLENGTH_"+i; colResult.setMinLength(rs.getInt(lastSQL)); } if (findingMaxLength && pfd.isMaxLength() ) { lastSQL = "MAXLENGTH_"+i; colResult.setMaxLength(rs.getInt(lastSQL)); } if (findingAvgLength && pfd.isAvgLength() ) { lastSQL = "AVGLENGTH_"+i; colResult.setAvgLength(rs.getInt(lastSQL)); } if ( findingNullCount && pfd.isSumDecode() ) { lastSQL = "NULLCOUNT_"+i; colResult.setNullCount(rs.getInt(lastSQL)); } } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } i++; if (findingTopTen && pfd.isCountDist() ) { sql = new StringBuffer(); sql.append("SELECT \""); sql.append(col.getName()); sql.append("\" AS MYVALUE, COUNT(*) AS COUNT1 FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); sql.append(" GROUP BY \""); sql.append(col.getName()); sql.append("\" ORDER BY COUNT1 DESC"); colResult = (ColumnProfileResult) getResult(col); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); for ( int n=0; rs.next() && n < 10; n++ ) { colResult.addValueCount(rs.getObject("MYVALUE"), rs.getInt("COUNT1")); } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } } } // XXX: add where filter later } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } } } |
sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); | sql.append("\n FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(), table.getSchemaName(), table.getName(), databaseIdentifierQuoteString, databaseIdentifierQuoteString)); | private void doColumnProfile(List<SQLColumn> columns, Connection conn) throws SQLException { Statement stmt = null; ResultSet rs = null; String lastSQL = null; try { if ( columns.size() == 0 ) return; SQLColumn col1 = columns.get(0); DDLGenerator ddlg = null; Class generatorClass = null; try { Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); generatorClass = (Class) ddlGeneratorMap.get( col1.getParentTable().getParentDatabase().getDataSource().getDriverClass()); // FIXME: make warning user visable if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } ddlg = (DDLGenerator) generatorClass.newInstance(); } catch (InstantiationException e1) { logger.error("problem running Profile Manager", e1); } catch ( IllegalAccessException e1 ) { logger.error("problem running Profile Manager", e1); } stmt = conn.createStatement(); stmt.setEscapeProcessing(false); int i = 0; for (SQLColumn col : columns ) { ProfileFunctionDescriptor pfd = ddlg.getProfileFunctionMap().get(col.getSourceDataTypeName()); ColumnProfileResult colResult = new ColumnProfileResult(System.currentTimeMillis()); if ( pfd == null ) { System.out.println(col.getName()+ " Unknown DataType:(" + col.getSourceDataTypeName() + "). please setup the profile function mapping"); continue; } StringBuffer sql = new StringBuffer(); sql.append("SELECT 1"); if (findingDistinctCount && pfd.isCountDist() ) { sql.append(",\n COUNT(DISTINCT \""); sql.append(col.getName()); sql.append("\") AS DISTINCTCOUNT_"+i); } if (findingMin && pfd.isMinValue() ) { sql.append(",\n MIN(\""); sql.append(col.getName()); sql.append("\") AS MINVALUE_"+i); } if (findingMax && pfd.isMaxValus() ) { sql.append(",\n MAX(\""); sql.append(col.getName()); sql.append("\") AS MAXVALUE_"+i); } if (findingAvg && pfd.isAvgValue() ) { sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); } if (findingMinLength && pfd.isMinLength() ) { sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); } if (findingMaxLength && pfd.isMaxLength() ) { sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); } if (findingAvgLength && pfd.isAvgLength() ) { sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); } if ( findingNullCount && pfd.isSumDecode() ) { sql.append(",\n SUM("); sql.append(ddlg.caseWhen("\""+col.getName()+"\"", "NULL", "1")); sql.append(") AS NULLCOUNT_"+i); } SQLTable table = col.getParentTable(); sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { if (findingDistinctCount && pfd.isCountDist() ) { lastSQL = "DISTINCTCOUNT_"+i; colResult.setDistinctValueCount(rs.getInt(lastSQL)); } if (findingMin && pfd.isMinValue() ) { lastSQL = "MINVALUE_"+i; colResult.setMinValue(rs.getObject(lastSQL)); } if (findingMax && pfd.isMaxValus() ) { lastSQL = "MAXVALUE_"+i; colResult.setMaxValue(rs.getObject(lastSQL)); } if (findingAvg && pfd.isAvgValue() ) { lastSQL = "AVGVALUE_"+i; colResult.setAvgValue(rs.getObject(lastSQL)); } if (findingMinLength && pfd.isMinLength() ) { lastSQL = "MINLENGTH_"+i; colResult.setMinLength(rs.getInt(lastSQL)); } if (findingMaxLength && pfd.isMaxLength() ) { lastSQL = "MAXLENGTH_"+i; colResult.setMaxLength(rs.getInt(lastSQL)); } if (findingAvgLength && pfd.isAvgLength() ) { lastSQL = "AVGLENGTH_"+i; colResult.setAvgLength(rs.getInt(lastSQL)); } if ( findingNullCount && pfd.isSumDecode() ) { lastSQL = "NULLCOUNT_"+i; colResult.setNullCount(rs.getInt(lastSQL)); } } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } i++; if (findingTopTen && pfd.isCountDist() ) { sql = new StringBuffer(); sql.append("SELECT \""); sql.append(col.getName()); sql.append("\" AS MYVALUE, COUNT(*) AS COUNT1 FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); sql.append(" GROUP BY \""); sql.append(col.getName()); sql.append("\" ORDER BY COUNT1 DESC"); colResult = (ColumnProfileResult) getResult(col); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); for ( int n=0; rs.next() && n < 10; n++ ) { colResult.addValueCount(rs.getObject("MYVALUE"), rs.getInt("COUNT1")); } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } } } // XXX: add where filter later } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } } } |
sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); | sql.append(DDLUtils.toQualifiedName(table.getCatalogName(), table.getSchemaName(), table.getName(), databaseIdentifierQuoteString, databaseIdentifierQuoteString)); | private void doColumnProfile(List<SQLColumn> columns, Connection conn) throws SQLException { Statement stmt = null; ResultSet rs = null; String lastSQL = null; try { if ( columns.size() == 0 ) return; SQLColumn col1 = columns.get(0); DDLGenerator ddlg = null; Class generatorClass = null; try { Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); generatorClass = (Class) ddlGeneratorMap.get( col1.getParentTable().getParentDatabase().getDataSource().getDriverClass()); // FIXME: make warning user visable if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } ddlg = (DDLGenerator) generatorClass.newInstance(); } catch (InstantiationException e1) { logger.error("problem running Profile Manager", e1); } catch ( IllegalAccessException e1 ) { logger.error("problem running Profile Manager", e1); } stmt = conn.createStatement(); stmt.setEscapeProcessing(false); int i = 0; for (SQLColumn col : columns ) { ProfileFunctionDescriptor pfd = ddlg.getProfileFunctionMap().get(col.getSourceDataTypeName()); ColumnProfileResult colResult = new ColumnProfileResult(System.currentTimeMillis()); if ( pfd == null ) { System.out.println(col.getName()+ " Unknown DataType:(" + col.getSourceDataTypeName() + "). please setup the profile function mapping"); continue; } StringBuffer sql = new StringBuffer(); sql.append("SELECT 1"); if (findingDistinctCount && pfd.isCountDist() ) { sql.append(",\n COUNT(DISTINCT \""); sql.append(col.getName()); sql.append("\") AS DISTINCTCOUNT_"+i); } if (findingMin && pfd.isMinValue() ) { sql.append(",\n MIN(\""); sql.append(col.getName()); sql.append("\") AS MINVALUE_"+i); } if (findingMax && pfd.isMaxValus() ) { sql.append(",\n MAX(\""); sql.append(col.getName()); sql.append("\") AS MAXVALUE_"+i); } if (findingAvg && pfd.isAvgValue() ) { sql.append(",\n AVG(\""); sql.append(col.getName()); sql.append("\") AS AVGVALUE_"+i); } if (findingMinLength && pfd.isMinLength() ) { sql.append(",\n MIN(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MINLENGTH_"+i); } if (findingMaxLength && pfd.isMaxLength() ) { sql.append(",\n MAX(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS MAXLENGTH_"+i); } if (findingAvgLength && pfd.isAvgLength() ) { sql.append(",\n AVG(LENGTH(\""); sql.append(col.getName()); sql.append("\")) AS AVGLENGTH_"+i); } if ( findingNullCount && pfd.isSumDecode() ) { sql.append(",\n SUM("); sql.append(ddlg.caseWhen("\""+col.getName()+"\"", "NULL", "1")); sql.append(") AS NULLCOUNT_"+i); } SQLTable table = col.getParentTable(); sql.append("\n FROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { if (findingDistinctCount && pfd.isCountDist() ) { lastSQL = "DISTINCTCOUNT_"+i; colResult.setDistinctValueCount(rs.getInt(lastSQL)); } if (findingMin && pfd.isMinValue() ) { lastSQL = "MINVALUE_"+i; colResult.setMinValue(rs.getObject(lastSQL)); } if (findingMax && pfd.isMaxValus() ) { lastSQL = "MAXVALUE_"+i; colResult.setMaxValue(rs.getObject(lastSQL)); } if (findingAvg && pfd.isAvgValue() ) { lastSQL = "AVGVALUE_"+i; colResult.setAvgValue(rs.getObject(lastSQL)); } if (findingMinLength && pfd.isMinLength() ) { lastSQL = "MINLENGTH_"+i; colResult.setMinLength(rs.getInt(lastSQL)); } if (findingMaxLength && pfd.isMaxLength() ) { lastSQL = "MAXLENGTH_"+i; colResult.setMaxLength(rs.getInt(lastSQL)); } if (findingAvgLength && pfd.isAvgLength() ) { lastSQL = "AVGLENGTH_"+i; colResult.setAvgLength(rs.getInt(lastSQL)); } if ( findingNullCount && pfd.isSumDecode() ) { lastSQL = "NULLCOUNT_"+i; colResult.setNullCount(rs.getInt(lastSQL)); } } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } i++; if (findingTopTen && pfd.isCountDist() ) { sql = new StringBuffer(); sql.append("SELECT \""); sql.append(col.getName()); sql.append("\" AS MYVALUE, COUNT(*) AS COUNT1 FROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); sql.append(" GROUP BY \""); sql.append(col.getName()); sql.append("\" ORDER BY COUNT1 DESC"); colResult = (ColumnProfileResult) getResult(col); try { lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); for ( int n=0; rs.next() && n < 10; n++ ) { colResult.addValueCount(rs.getObject("MYVALUE"), rs.getInt("COUNT1")); } } catch ( SQLException ex ) { colResult.setError(true); colResult.setEx(ex); logger.error("Error in Column Profiling: "+lastSQL, ex); } finally { colResult.setCreateEndTime(System.currentTimeMillis()); putResult(col, colResult); try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } rs = null; } } } // XXX: add where filter later } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } } } |
databaseIdentifierQuoteString = conn.getMetaData().getIdentifierQuoteString(); | private void doTableProfile(SQLTable table) throws SQLException, ArchitectException { SQLDatabase db = table.getParentDatabase(); Connection conn = null; Statement stmt = null; ResultSet rs = null; String lastSQL = null; TableProfileResult tableResult = new TableProfileResult(System.currentTimeMillis()); try { conn = db.getConnection(); Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); Class generatorClass = (Class) ddlGeneratorMap.get( db.getDataSource().getDriverClass()); if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } StringBuffer sql = new StringBuffer(); sql.append("SELECT COUNT(*) AS ROWCOUNT"); sql.append("\nFROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); stmt = conn.createStatement(); stmt.setEscapeProcessing(false); lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { tableResult.setCreateEndTime(System.currentTimeMillis()); tableResult.setRowCount(rs.getInt("ROWCOUNT")); } rs.close(); rs = null; doColumnProfile(table.getColumns(), conn); // XXX: add where filter later } catch (SQLException ex) { logger.error("Error in SQL query: "+lastSQL, ex); tableResult.setError(true); tableResult.setEx(ex); } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } try { if (conn != null) conn.close(); } catch (SQLException ex) { logger.error("Couldn't clean up connection", ex); } putResult(table, tableResult); } } |
|
sql.append("SELECT COUNT(*) AS ROWCOUNT"); sql.append("\nFROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); | sql.append("SELECT COUNT(*) AS ROW__COUNT"); sql.append("\nFROM "); sql.append(DDLUtils.toQualifiedName(table.getCatalogName(), table.getSchemaName(), table.getName(), databaseIdentifierQuoteString, databaseIdentifierQuoteString)); | private void doTableProfile(SQLTable table) throws SQLException, ArchitectException { SQLDatabase db = table.getParentDatabase(); Connection conn = null; Statement stmt = null; ResultSet rs = null; String lastSQL = null; TableProfileResult tableResult = new TableProfileResult(System.currentTimeMillis()); try { conn = db.getConnection(); Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); Class generatorClass = (Class) ddlGeneratorMap.get( db.getDataSource().getDriverClass()); if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } StringBuffer sql = new StringBuffer(); sql.append("SELECT COUNT(*) AS ROWCOUNT"); sql.append("\nFROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); stmt = conn.createStatement(); stmt.setEscapeProcessing(false); lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { tableResult.setCreateEndTime(System.currentTimeMillis()); tableResult.setRowCount(rs.getInt("ROWCOUNT")); } rs.close(); rs = null; doColumnProfile(table.getColumns(), conn); // XXX: add where filter later } catch (SQLException ex) { logger.error("Error in SQL query: "+lastSQL, ex); tableResult.setError(true); tableResult.setEx(ex); } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } try { if (conn != null) conn.close(); } catch (SQLException ex) { logger.error("Couldn't clean up connection", ex); } putResult(table, tableResult); } } |
tableResult.setRowCount(rs.getInt("ROWCOUNT")); | tableResult.setRowCount(rs.getInt("ROW__COUNT")); | private void doTableProfile(SQLTable table) throws SQLException, ArchitectException { SQLDatabase db = table.getParentDatabase(); Connection conn = null; Statement stmt = null; ResultSet rs = null; String lastSQL = null; TableProfileResult tableResult = new TableProfileResult(System.currentTimeMillis()); try { conn = db.getConnection(); Map ddlGeneratorMap = ArchitectUtils.getDriverDDLGeneratorMap(); Class generatorClass = (Class) ddlGeneratorMap.get( db.getDataSource().getDriverClass()); if (generatorClass == null) { System.out.println("Unable to create Profile for the target database."); return; } StringBuffer sql = new StringBuffer(); sql.append("SELECT COUNT(*) AS ROWCOUNT"); sql.append("\nFROM ").append(DDLUtils.toQualifiedName(table.getCatalogName(),table.getSchemaName(),table.getName())); stmt = conn.createStatement(); stmt.setEscapeProcessing(false); lastSQL = sql.toString(); rs = stmt.executeQuery(lastSQL); if ( rs.next() ) { tableResult.setCreateEndTime(System.currentTimeMillis()); tableResult.setRowCount(rs.getInt("ROWCOUNT")); } rs.close(); rs = null; doColumnProfile(table.getColumns(), conn); // XXX: add where filter later } catch (SQLException ex) { logger.error("Error in SQL query: "+lastSQL, ex); tableResult.setError(true); tableResult.setEx(ex); } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.error("Couldn't clean up result set", ex); } try { if (stmt != null) stmt.close(); } catch (SQLException ex) { logger.error("Couldn't clean up statement", ex); } try { if (conn != null) conn.close(); } catch (SQLException ex) { logger.error("Couldn't clean up connection", ex); } putResult(table, tableResult); } } |
return columnProfile.getNullCount() == 0 ? null : columnProfile.getNullCount() * 100D / rowCount ; | return rowCount == 0 ? null : (double)columnProfile.getNullCount() / rowCount ; | public Object getValueAt(int rowIndex, int columnIndex) { ColumnProfileResult columnProfile = resultList.get(rowIndex); SQLColumn col = columnProfile.getProfiledObject(); int rowCount = ((TableProfileResult) profileManager.getResult(col.getParentTable())).getRowCount(); if (columnIndex == 0) { return ArchitectUtils.getAncestor(col,SQLDatabase.class); } else if (columnIndex == 1) { return ArchitectUtils.getAncestor(col,SQLCatalog.class); } else if (columnIndex == 2) { return ArchitectUtils.getAncestor(col,SQLSchema.class); } else if (columnIndex == 3) { return ArchitectUtils.getAncestor(col,SQLTable.class); } else if (columnIndex == 4) { return col; } else if (columnIndex == 5) { // Run date return columnProfile.getCreateStartTime(); } else if (columnIndex == 6) { // Row Count return rowCount; } else if (columnIndex == 7) { // data type DDLGenerator gddl; try { gddl = DDLUtils.createDDLGenerator(col.getParentTable().getParentDatabase().getDataSource()); return gddl.columnType(col); } catch (Exception e) { throw new ArchitectRuntimeException(new ArchitectException( "Unable to get DDL information. Do we have a valid data source?", e)); } } else if (columnIndex == 8) { // Number of null records return columnProfile.getNullCount(); } else if (columnIndex == 9) { // Percent null records return columnProfile.getNullCount() == 0 ? null : columnProfile.getNullCount() * 100D / rowCount ; } else if (columnIndex == 10) { // Number of unique records return columnProfile.getDistinctValueCount(); } else if (columnIndex == 11) { // percent of unique records return columnProfile.getDistinctValueCount() == 0 ? null : columnProfile.getDistinctValueCount() * 100D / rowCount; } else if (columnIndex == 12) { // min Length return columnProfile.getMinLength(); } else if (columnIndex == 13) { // Max Length return columnProfile.getMaxLength(); } else if (columnIndex == 14) { // Avg Length return columnProfile.getAvgLength(); } else if (columnIndex == 15) { // min Value return columnProfile.getMinValue(); } else if (columnIndex == 16) { // Max value return columnProfile.getMaxValue(); } else if (columnIndex == 17) { // Avg Value return columnProfile.getAvgValue(); } else { throw new IllegalArgumentException("Column Index out of bounds"); } } |
return columnProfile.getDistinctValueCount() == 0 ? null : columnProfile.getDistinctValueCount() * 100D / rowCount; | return rowCount == 0 ? null : (double)columnProfile.getDistinctValueCount() / rowCount; | public Object getValueAt(int rowIndex, int columnIndex) { ColumnProfileResult columnProfile = resultList.get(rowIndex); SQLColumn col = columnProfile.getProfiledObject(); int rowCount = ((TableProfileResult) profileManager.getResult(col.getParentTable())).getRowCount(); if (columnIndex == 0) { return ArchitectUtils.getAncestor(col,SQLDatabase.class); } else if (columnIndex == 1) { return ArchitectUtils.getAncestor(col,SQLCatalog.class); } else if (columnIndex == 2) { return ArchitectUtils.getAncestor(col,SQLSchema.class); } else if (columnIndex == 3) { return ArchitectUtils.getAncestor(col,SQLTable.class); } else if (columnIndex == 4) { return col; } else if (columnIndex == 5) { // Run date return columnProfile.getCreateStartTime(); } else if (columnIndex == 6) { // Row Count return rowCount; } else if (columnIndex == 7) { // data type DDLGenerator gddl; try { gddl = DDLUtils.createDDLGenerator(col.getParentTable().getParentDatabase().getDataSource()); return gddl.columnType(col); } catch (Exception e) { throw new ArchitectRuntimeException(new ArchitectException( "Unable to get DDL information. Do we have a valid data source?", e)); } } else if (columnIndex == 8) { // Number of null records return columnProfile.getNullCount(); } else if (columnIndex == 9) { // Percent null records return columnProfile.getNullCount() == 0 ? null : columnProfile.getNullCount() * 100D / rowCount ; } else if (columnIndex == 10) { // Number of unique records return columnProfile.getDistinctValueCount(); } else if (columnIndex == 11) { // percent of unique records return columnProfile.getDistinctValueCount() == 0 ? null : columnProfile.getDistinctValueCount() * 100D / rowCount; } else if (columnIndex == 12) { // min Length return columnProfile.getMinLength(); } else if (columnIndex == 13) { // Max Length return columnProfile.getMaxLength(); } else if (columnIndex == 14) { // Avg Length return columnProfile.getAvgLength(); } else if (columnIndex == 15) { // min Value return columnProfile.getMinValue(); } else if (columnIndex == 16) { // Max value return columnProfile.getMaxValue(); } else if (columnIndex == 17) { // Avg Value return columnProfile.getAvgValue(); } else { throw new IllegalArgumentException("Column Index out of bounds"); } } |
for (int i = 0; i < getComponentCount(); i++) { Component c = getComponent(i); | for (int i = 0; i < contentPane.getComponentCount(); i++) { Component c = contentPane.getComponent(i); | public TablePane findTablePane(SQLTable t) { for (int i = 0; i < getComponentCount(); i++) { Component c = getComponent(i); if (c instanceof TablePane && ((TablePane) c).getModel() == t) { return (TablePane) c; } } return null; } |
JLabel renderer = (JLabel) getCellRenderer(row, col).getTableCellRendererComponent(this, getModel().getValueAt(row, col), false, false, row, col); | JLabel renderer = (JLabel) getCellRenderer(row, col).getTableCellRendererComponent(this, getModel().getValueAt(row, getColumnModel().getColumn(col).getModelIndex()), false, false, row, col); | public String getTextForCell(int row, int col) { // note: this will only work because we know all the renderers are jlabels JLabel renderer = (JLabel) getCellRenderer(row, col).getTableCellRendererComponent(this, getModel().getValueAt(row, col), false, false, row, col); return renderer.getText(); } |
Object value = expression.evaluate(context); | Class type = dynaTag.getAttributeType(name); Object value = null; if (type != null && type.isAssignableFrom(Expression.class) && !type.isAssignableFrom(Object.class)) { value = expression; } else { value = expression.evaluate(context); } | public void run(JellyContext context, XMLOutput output) throws Exception { if ( ! context.isCacheTags() ) { clearTag(); } try { Tag tag = getTag(); if ( tag == null ) { return; } tag.setContext(context); if ( tag instanceof DynaTag ) { DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } } else { // treat the tag as a bean DynaBean dynaBean = new ConvertingWrapDynaBean( tag ); for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaBean.set(name, value); } } tag.doTag(output); } catch (JellyException e) { handleException(e); } catch (Exception e) { handleException(e); } } |
if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ if(momAllele1 == momAllele2){ if (dadAllele1 == dadAllele2){ if (momAllele1 == dadAllele1){ if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else{ if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; | if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ if(currentInd.getGender() == 1) { if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0)){ if(allele1 != momAllele1 && allele1 != momAllele2) { mendErrNum ++; | private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; } |
}else{ if (dadAllele1 == dadAllele2){ if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; | }else { if(momAllele1 == momAllele2) { if(dadAllele1 == momAllele1) { if(allele1 != momAllele1 || allele2 != momAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else { if(allele1 == allele2 ){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ if(allele1 != dadAllele1 && allele2 != dadAllele2){ mendErrNum ++; | private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; } |
} }else{ if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ if(momAllele1 == momAllele2){ if (dadAllele1 == dadAllele2){ if (momAllele1 == dadAllele1){ if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else{ if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ if (dadAllele1 == dadAllele2){ if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } } | private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; } |
|
this.path = path; | this.path = (path != null ) ? path.clone() : null; | public PhotoFolderEvent( PhotoFolder source, PhotoFolder subfolder, PhotoFolder[] path ) { super( source ); this.subfolder = subfolder; this.path = path; } |
} | } finally { event.getSQLSource().setMagicEnabled(true); } | public void redo() throws CannotRedoException { try { modifyProperty(event.getNewValue()); } catch (IllegalAccessException e) { logger.error("Couldn't access setter for "+ event.getPropertyName(), e); throw new CannotRedoException(); } catch (InvocationTargetException e) { logger.error("Setter for "+event.getPropertyName()+ " on "+event.getSource()+" threw exception", e); throw new CannotRedoException(); } catch (IntrospectionException e) { logger.error("Couldn't introspect source object "+ event.getSource(), e); throw new CannotRedoException(); } super.redo(); } |
} | } finally { event.getSQLSource().setMagicEnabled(true); } | public void undo() throws CannotUndoException { try { modifyProperty(event.getOldValue()); } catch (IllegalAccessException e) { logger.error("Couldn't access setter for "+ event.getPropertyName(), e); throw new CannotUndoException(); } catch (InvocationTargetException e) { logger.error("Setter for "+event.getPropertyName()+ " on "+event.getSource()+" threw exception", e); throw new CannotUndoException(); } catch (IntrospectionException e) { logger.error("Couldn't introspect source object "+ event.getSource(), e); throw new CannotUndoException(); } super.undo(); } |
fit(); | SwingUtilities.invokeLater( new java.lang.Runnable() { public void run() { fit(); } } ); | public void componentResized( ComponentEvent e) { if ( isFit ) { fit(); } } |
public SwingUIProject(String name) { | public SwingUIProject(String name) throws ArchitectException { | public SwingUIProject(String name) { this.name = name; this.sourceDatabases = new ArrayList(); this.targetDatabase = new SQLDatabase(); } |
this.sourceDatabases = new ArrayList(); this.targetDatabase = new SQLDatabase(); | this.playPen = new PlayPen(new SQLDatabase()); List initialDBList = new ArrayList(); initialDBList.add(playPen.getDatabase()); this.sourceDatabases = new DBTree(initialDBList); | public SwingUIProject(String name) { this.name = name; this.sourceDatabases = new ArrayList(); this.targetDatabase = new SQLDatabase(); } |
public List getSourceDatabases() { | public DBTree getSourceDatabases() { | public List getSourceDatabases() { return this.sourceDatabases; } |
return this.targetDatabase; | return playPen.getDatabase(); | public SQLDatabase getTargetDatabase() { return this.targetDatabase; } |
public void setSourceDatabases(List argSourceDatabases) { | public void setSourceDatabases(DBTree argSourceDatabases) { | public void setSourceDatabases(List argSourceDatabases) { this.sourceDatabases = argSourceDatabases; } |
if (!location.canRead()) { throw new IllegalArgumentException("pl.ini file cannot be read: " + location.getAbsolutePath()); } lastFileRead = location; ArchitectDataSource currentDS = null; Section currentSection = new Section(null); fileSections.add(currentSection); fileTime = location.lastModified(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(location)); byte[] lineBytes = null; while ((lineBytes = readLine(in)) != null) { String line = new String(lineBytes); logger.debug("Read in new line: "+line); if (line.startsWith("[Databases_")) { logger.debug("It's a new database connection spec!"); currentDS = new ArchitectDataSource(); add(currentDS); mode = MODE_READ_DS; } else if (line.startsWith("[")) { logger.debug("It's a new generic section!"); currentSection = new Section(line.substring(1, line.length()-1)); fileSections.add(currentSection); mode = MODE_READ_GENERIC; } else { String key; String value; int equalsIdx = line.indexOf('='); if (equalsIdx > 0) { key = line.substring(0, equalsIdx); value = line.substring(equalsIdx+1, line.length()); } else { key = line; value = null; } logger.debug("key="+key+",val="+value); if (mode == MODE_READ_DS) { if (key.equals("PWD") && value != null) { byte[] cypherBytes = new byte[lineBytes.length - equalsIdx - 1]; System.arraycopy(lineBytes, equalsIdx + 1, cypherBytes, 0, cypherBytes.length); value = decryptPassword(9, cypherBytes); } currentDS.put(key, value); } else if (mode == MODE_READ_GENERIC) { currentSection.put(key, value); } } } in.close(); | try { dontAutoSave = true; if (!location.canRead()) { throw new IllegalArgumentException("pl.ini file cannot be read: " + location.getAbsolutePath()); } lastFileAccessed = location; ArchitectDataSource currentDS = null; Section currentSection = new Section(null); fileSections.add(currentSection); fileTime = location.lastModified(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(location)); byte[] lineBytes = null; while ((lineBytes = readLine(in)) != null) { String line = new String(lineBytes); logger.debug("Read in new line: "+line); if (line.startsWith("[Databases_")) { logger.debug("It's a new database connection spec!"); currentDS = new ArchitectDataSource(); add(currentDS); mode = MODE_READ_DS; } else if (line.startsWith("[")) { logger.debug("It's a new generic section!"); currentSection = new Section(line.substring(1, line.length()-1)); fileSections.add(currentSection); mode = MODE_READ_GENERIC; } else { String key; String value; int equalsIdx = line.indexOf('='); if (equalsIdx > 0) { key = line.substring(0, equalsIdx); value = line.substring(equalsIdx+1, line.length()); } else { key = line; value = null; } logger.debug("key="+key+",val="+value); if (mode == MODE_READ_DS) { if (key.equals("PWD") && value != null) { byte[] cypherBytes = new byte[lineBytes.length - equalsIdx - 1]; System.arraycopy(lineBytes, equalsIdx + 1, cypherBytes, 0, cypherBytes.length); value = decryptPassword(9, cypherBytes); } currentDS.put(key, value); } else if (mode == MODE_READ_GENERIC) { currentSection.put(key, value); } } } in.close(); } finally { dontAutoSave = false; } | public void read(File location) throws IOException { final int MODE_READ_DS = 0; // reading a data source section final int MODE_READ_GENERIC = 1; // reading a generic named section int mode = MODE_READ_GENERIC; if (!location.canRead()) { throw new IllegalArgumentException("pl.ini file cannot be read: " + location.getAbsolutePath()); } lastFileRead = location; ArchitectDataSource currentDS = null; Section currentSection = new Section(null); // this accounts for any properties before the first named section fileSections.add(currentSection); fileTime = location.lastModified(); // Can't use Reader to read this file because the encrypted passwords contain non-ASCII characters BufferedInputStream in = new BufferedInputStream(new FileInputStream(location)); byte[] lineBytes = null; while ((lineBytes = readLine(in)) != null) { String line = new String(lineBytes); logger.debug("Read in new line: "+line); if (line.startsWith("[Databases_")) { logger.debug("It's a new database connection spec!"); currentDS = new ArchitectDataSource(); add(currentDS); mode = MODE_READ_DS; } else if (line.startsWith("[")) { logger.debug("It's a new generic section!"); currentSection = new Section(line.substring(1, line.length()-1)); fileSections.add(currentSection); mode = MODE_READ_GENERIC; } else { String key; String value; int equalsIdx = line.indexOf('='); if (equalsIdx > 0) { key = line.substring(0, equalsIdx); value = line.substring(equalsIdx+1, line.length()); } else { key = line; value = null; } logger.debug("key="+key+",val="+value); if (mode == MODE_READ_DS) { if (key.equals("PWD") && value != null) { byte[] cypherBytes = new byte[lineBytes.length - equalsIdx - 1]; System.arraycopy(lineBytes, equalsIdx + 1, cypherBytes, 0, cypherBytes.length); value = decryptPassword(9, cypherBytes); } currentDS.put(key, value); } else if (mode == MODE_READ_GENERIC) { currentSection.put(key, value); } } } in.close(); if (logger.isDebugEnabled()) logger.debug("Finished reading file. Parsed contents:\n"+toString()); } |
OutputStream out = new BufferedOutputStream(new FileOutputStream(location)); write(out); out.close(); fileTime = location.lastModified(); | try { dontAutoSave = true; OutputStream out = new BufferedOutputStream(new FileOutputStream(location)); write(out); out.close(); lastFileAccessed = location; fileTime = location.lastModified(); } finally { dontAutoSave = false; } | public void write(File location) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(location)); write(out); out.close(); fileTime = location.lastModified(); } |
public void writeSection(OutputStream out, String name, Map properties) throws IOException { | private void writeSection(OutputStream out, String name, Map properties) throws IOException { | public void writeSection(OutputStream out, String name, Map properties) throws IOException { if (name != null) { String sectionHeading = "["+name+"]" + DOS_CR_LF; out.write(sectionHeading.getBytes()); } // output LOGICAL first (if it exists) String s = null; if ((s = (String) properties.get("Logical")) != null) { out.write("Logical".getBytes()); out.write("=".getBytes()); out.write(s.getBytes()); out.write(DOS_CR_LF.getBytes()); } // now get everything else, and ignore the LOGICAL property Iterator it = properties.entrySet().iterator(); while (it.hasNext()) { Map.Entry ent = (Map.Entry) it.next(); if (!ent.getKey().equals("Logical")) { out.write(((String) ent.getKey()).getBytes()); if (ent.getValue() != null) { byte[] val; if (ent.getKey().equals("PWD")) { val = encryptPassword(9, ((String) ent.getValue())); } else { val = ((String) ent.getValue()).getBytes(); } out.write("=".getBytes()); out.write(val); } out.write(DOS_CR_LF.getBytes()); } } } |
public String put(String key, String value) { String oldValue = get(key); properties.put(key,value); getPcs().firePropertyChange(key,oldValue,value); return oldValue; | public String put(String key, String value) { return putImpl(key, value, key); | public String put(String key, String value) { String oldValue = get(key); properties.put(key,value); getPcs().firePropertyChange(key,oldValue,value); return oldValue; } |
db.addVolume( v ); | try { db.addVolume( v ); } catch (PhotovaultException ex) { fail( ex.getMessage() ); } | public void testVolumeAddition() { PVDatabase db = new PVDatabase(); db.setDbHost( "" ); db.setDbName( "test" ); Volume v = new Volume( "test", "c:/temp" ); db.addVolume( v ); List volumes = db.getVolumes(); assertTrue( volumes.get( 0 ) == v ); assertTrue( volumes.size() == 1 ); } |
db.addVolume( v ); | public void testXMLOutput() { PVDatabase db = new PVDatabase(); db.setDbHost( "" ); db.setDbName( "test" ); Volume v = new Volume( "test", "c:/temp/voltest" ); db.addVolume( v ); ExternalVolume ev = new ExternalVolume( "test_extvol", "c./tem/extvoltest" ); db.addVolume( ev ); File tempFile = null; try { tempFile = File.createTempFile( "pv_settings_", ".xml" ); tempFile.deleteOnExit(); } catch ( Exception e ) { this.fail( e.getMessage() ); } try { BufferedWriter outputWriter = new BufferedWriter( new FileWriter( tempFile )); outputWriter.write("<?xml version='1.0' ?>\n"); BeanWriter beanWriter = new BeanWriter(outputWriter); beanWriter.getXMLIntrospector().setAttributesForPrimitives(true); beanWriter.setWriteIDs(false); beanWriter.enablePrettyPrint(); beanWriter.write("database", db); beanWriter.close(); } catch( Exception e ) { this.fail( e.getMessage() ); } // Now try to read the info BeanReader beanReader = new BeanReader(); beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(true); beanReader.getBindingConfiguration().setMapIDs(false); try { beanReader.registerBeanClass( "database", PVDatabase.class ); beanReader.registerBeanClass( "volume", Volume.class ); beanReader.registerBeanClass( "external-volume", ExternalVolume.class ); PVDatabase readDB = (PVDatabase) beanReader.parse( tempFile ); assertEquals( readDB.getDbName(), "test" ); List readVolumes = readDB.getVolumes(); assertTrue( readVolumes.size() == 2 ); Volume readVolume = (Volume) readVolumes.get(0); assertEquals( readVolume.getName(), "test" ); assertEquals( readVolume.getBaseDir(), v.getBaseDir() ); ExternalVolume readExtVolume = (ExternalVolume) readVolumes.get(1); assertEquals( ev.getName(), readExtVolume.getName() ); assertEquals( ev.getBaseDir(), readExtVolume.getBaseDir() ); } catch ( Exception e ) { this.fail( e.getMessage() ); } } |
|
db.addVolume( ev ); | try { db.addVolume( v ); db.addVolume( ev ); } catch (PhotovaultException ex) { fail( ex.getMessage() ); } | public void testXMLOutput() { PVDatabase db = new PVDatabase(); db.setDbHost( "" ); db.setDbName( "test" ); Volume v = new Volume( "test", "c:/temp/voltest" ); db.addVolume( v ); ExternalVolume ev = new ExternalVolume( "test_extvol", "c./tem/extvoltest" ); db.addVolume( ev ); File tempFile = null; try { tempFile = File.createTempFile( "pv_settings_", ".xml" ); tempFile.deleteOnExit(); } catch ( Exception e ) { this.fail( e.getMessage() ); } try { BufferedWriter outputWriter = new BufferedWriter( new FileWriter( tempFile )); outputWriter.write("<?xml version='1.0' ?>\n"); BeanWriter beanWriter = new BeanWriter(outputWriter); beanWriter.getXMLIntrospector().setAttributesForPrimitives(true); beanWriter.setWriteIDs(false); beanWriter.enablePrettyPrint(); beanWriter.write("database", db); beanWriter.close(); } catch( Exception e ) { this.fail( e.getMessage() ); } // Now try to read the info BeanReader beanReader = new BeanReader(); beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(true); beanReader.getBindingConfiguration().setMapIDs(false); try { beanReader.registerBeanClass( "database", PVDatabase.class ); beanReader.registerBeanClass( "volume", Volume.class ); beanReader.registerBeanClass( "external-volume", ExternalVolume.class ); PVDatabase readDB = (PVDatabase) beanReader.parse( tempFile ); assertEquals( readDB.getDbName(), "test" ); List readVolumes = readDB.getVolumes(); assertTrue( readVolumes.size() == 2 ); Volume readVolume = (Volume) readVolumes.get(0); assertEquals( readVolume.getName(), "test" ); assertEquals( readVolume.getBaseDir(), v.getBaseDir() ); ExternalVolume readExtVolume = (ExternalVolume) readVolumes.get(1); assertEquals( ev.getName(), readExtVolume.getName() ); assertEquals( ev.getBaseDir(), readExtVolume.getBaseDir() ); } catch ( Exception e ) { this.fail( e.getMessage() ); } } |
if (isExportLibraries() && parent != null) { parent.registerTagLibrary( namespaceURI, taglib ); } | public void registerTagLibrary(String namespaceURI, TagLibrary taglib) { if (log.isDebugEnabled()) { log.debug("Registering tag library to: " + namespaceURI + " taglib: " + taglib); } taglibs.put(namespaceURI, taglib); } |
|
public void run(Context context, XMLOutput output) throws Exception { | public void run(JellyContext context, XMLOutput output) throws Exception { | public void run(Context context, XMLOutput output) throws Exception { if ( uri == null ) { throw new JellyException( "<j:include> must have a 'uri' attribute defined" ); } // we need to create a new Context of the URI // take off the script name from the URL context.runScript( uri, output ); } |
out.println("GO"); | println("GO"); | public void writeDDLTransactionEnd() { out.println("GO"); } |
out.println("-- Created by SQLPower SQLServer 2000 DDL Generator "+GENERATOR_VERSION+" --"); | println("-- Created by SQLPower SQLServer 2000 DDL Generator "+GENERATOR_VERSION+" --"); | public void writeHeader() { out.println("-- Created by SQLPower SQLServer 2000 DDL Generator "+GENERATOR_VERSION+" --"); } |
line.append(theTag.getName()).append("\t"); line.append(getPairwiseCompRsq(snp,theTag.getSequence())).append("\t"); | if(theTag != null) { line.append(theTag.getName()).append("\t"); line.append(getPairwiseCompRsq(snp,theTag.getSequence())).append("\t"); } | public void saveResultToFile(File outFile) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); bw.write("#tagging with r^2 cutoff: " + minRSquared); bw.newLine(); bw.write("Marker\tBest Tag\tr^2 w/tag"); bw.newLine(); for (int i = 0; i < snps.size(); i++) { StringBuffer line = new StringBuffer(); SNP snp = (SNP) snps.elementAt(i); line.append(snp.getName()).append("\t"); TagSequence theTag = snp.getBestTag(); line.append(theTag.getName()).append("\t"); line.append(getPairwiseCompRsq(snp,theTag.getSequence())).append("\t"); bw.write(line.toString()); bw.newLine(); } bw.newLine(); bw.write("Tag\tMarkers Tagged"); bw.newLine(); for(int i=0;i<tags.size();i++) { StringBuffer line = new StringBuffer(); TagSequence theTag = (TagSequence) tags.get(i); line.append(theTag.getName()).append("\t"); Vector tagged = theTag.getBestTagged(); for (int j = 0; j < tagged.size(); j++) { VariantSequence varSeq = (VariantSequence) tagged.elementAt(j); if(j !=0){ line.append(","); } line.append(varSeq.getName()); } bw.write(line.toString()); bw.newLine(); } bw.close(); } |
log.info("valid matches: " + m_results.getValidMails()); | private void logElapsedData() { log.info("unmatched messages: " + m_results.getUnmatchedMails()); log.info("matched messages: " + m_results.getMatchedMails()); log.info("recorded errors: " + m_results.getErrorCount()); } |
|
setLayout(new BorderLayout()); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); | protected void createUI() { tabPane = new JTabbedPane(); add( tabPane ); // General pane JPanel generalPane = new JPanel(); tabPane.addTab( "General", generalPane ); // Create the fields & their labels // Photographer field JLabel photographerLabel = new JLabel( "Photographer" ); photographerField = new JTextField( 30 ); photographerDoc = photographerField.getDocument(); photographerDoc.addDocumentListener( this ); photographerDoc.putProperty( FIELD_NAME, PhotoInfoController.PHOTOGRAPHER ); // Shooting date field JLabel shootingDayLabel = new JLabel( "Shooting date" ); DateFormat df = DateFormat.getDateInstance(); DateFormatter shootingDayFormatter = new DateFormatter( df ); shootingDayField = new JFormattedTextField( df ); shootingDayField.setColumns( 10 ); shootingDayField.setValue( new Date( )); shootingDayField.addPropertyChangeListener( this ); shootingDayField.putClientProperty( FIELD_NAME, PhotoInfoController.SHOOTING_DATE ); // Shooting place field JLabel shootingPlaceLabel = new JLabel( "Shooting place" ); shootingPlaceField = new JTextField( 30 ); shootingPlaceDoc = shootingPlaceField.getDocument(); shootingPlaceDoc.addDocumentListener( this ); shootingPlaceDoc.putProperty( FIELD_NAME, PhotoInfoController.SHOOTING_PLACE ); // Description text JLabel descLabel = new JLabel( "Description" ); descriptionTextArea = new JTextArea( 5, 40 ); descriptionTextArea.setLineWrap( true ); descriptionTextArea.setWrapStyleWord( true ); JScrollPane descScrollPane = new JScrollPane( descriptionTextArea ); descScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); Border descBorder = BorderFactory.createEtchedBorder( EtchedBorder.LOWERED ); descBorder = BorderFactory.createTitledBorder( descBorder, "Description" ); descScrollPane.setBorder( descBorder ); descriptionDoc = descriptionTextArea.getDocument(); descriptionDoc.putProperty( FIELD_NAME, PhotoInfoController.DESCRIPTION ); descriptionDoc.addDocumentListener( this ); // Save button JButton saveBtn = new JButton( "Save" ); saveBtn.setActionCommand( "save" ); saveBtn.addActionListener( this ); // Discard button JButton discardBtn = new JButton( "Discard" ); discardBtn.setActionCommand( "discard" ); discardBtn.addActionListener( this ); // Lay out the created controls GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); generalPane.setLayout( layout ); JLabel[] labels = { photographerLabel, shootingDayLabel, shootingPlaceLabel }; JTextField[] fields = { photographerField, shootingDayField, shootingPlaceField }; addLabelTextRows( labels, fields, layout, generalPane ); generalPane.add( descScrollPane ); c.gridwidth = GridBagConstraints.REMAINDER; c.weighty = 0.5; c.fill = GridBagConstraints.NONE; layout.setConstraints( descScrollPane, c ); c = new GridBagConstraints(); c.gridwidth = 1; c.weighty = 0; c.fill = GridBagConstraints.NONE; c.gridy = GridBagConstraints.RELATIVE; generalPane.add( saveBtn ); layout.setConstraints( saveBtn, c ); c.gridy = GridBagConstraints.RELATIVE; generalPane.add( discardBtn ); layout.setConstraints( discardBtn, c ); createTechDataUI(); } |
|
add( tabPane ); | add( tabPane, BorderLayout.CENTER ); | protected void createUI() { tabPane = new JTabbedPane(); add( tabPane ); // General pane JPanel generalPane = new JPanel(); tabPane.addTab( "General", generalPane ); // Create the fields & their labels // Photographer field JLabel photographerLabel = new JLabel( "Photographer" ); photographerField = new JTextField( 30 ); photographerDoc = photographerField.getDocument(); photographerDoc.addDocumentListener( this ); photographerDoc.putProperty( FIELD_NAME, PhotoInfoController.PHOTOGRAPHER ); // Shooting date field JLabel shootingDayLabel = new JLabel( "Shooting date" ); DateFormat df = DateFormat.getDateInstance(); DateFormatter shootingDayFormatter = new DateFormatter( df ); shootingDayField = new JFormattedTextField( df ); shootingDayField.setColumns( 10 ); shootingDayField.setValue( new Date( )); shootingDayField.addPropertyChangeListener( this ); shootingDayField.putClientProperty( FIELD_NAME, PhotoInfoController.SHOOTING_DATE ); // Shooting place field JLabel shootingPlaceLabel = new JLabel( "Shooting place" ); shootingPlaceField = new JTextField( 30 ); shootingPlaceDoc = shootingPlaceField.getDocument(); shootingPlaceDoc.addDocumentListener( this ); shootingPlaceDoc.putProperty( FIELD_NAME, PhotoInfoController.SHOOTING_PLACE ); // Description text JLabel descLabel = new JLabel( "Description" ); descriptionTextArea = new JTextArea( 5, 40 ); descriptionTextArea.setLineWrap( true ); descriptionTextArea.setWrapStyleWord( true ); JScrollPane descScrollPane = new JScrollPane( descriptionTextArea ); descScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); Border descBorder = BorderFactory.createEtchedBorder( EtchedBorder.LOWERED ); descBorder = BorderFactory.createTitledBorder( descBorder, "Description" ); descScrollPane.setBorder( descBorder ); descriptionDoc = descriptionTextArea.getDocument(); descriptionDoc.putProperty( FIELD_NAME, PhotoInfoController.DESCRIPTION ); descriptionDoc.addDocumentListener( this ); // Save button JButton saveBtn = new JButton( "Save" ); saveBtn.setActionCommand( "save" ); saveBtn.addActionListener( this ); // Discard button JButton discardBtn = new JButton( "Discard" ); discardBtn.setActionCommand( "discard" ); discardBtn.addActionListener( this ); // Lay out the created controls GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); generalPane.setLayout( layout ); JLabel[] labels = { photographerLabel, shootingDayLabel, shootingPlaceLabel }; JTextField[] fields = { photographerField, shootingDayField, shootingPlaceField }; addLabelTextRows( labels, fields, layout, generalPane ); generalPane.add( descScrollPane ); c.gridwidth = GridBagConstraints.REMAINDER; c.weighty = 0.5; c.fill = GridBagConstraints.NONE; layout.setConstraints( descScrollPane, c ); c = new GridBagConstraints(); c.gridwidth = 1; c.weighty = 0; c.fill = GridBagConstraints.NONE; c.gridy = GridBagConstraints.RELATIVE; generalPane.add( saveBtn ); layout.setConstraints( saveBtn, c ); c.gridy = GridBagConstraints.RELATIVE; generalPane.add( discardBtn ); layout.setConstraints( discardBtn, c ); createTechDataUI(); } |
c.fill = GridBagConstraints.NONE; | c.fill = GridBagConstraints.BOTH; | protected void createUI() { tabPane = new JTabbedPane(); add( tabPane ); // General pane JPanel generalPane = new JPanel(); tabPane.addTab( "General", generalPane ); // Create the fields & their labels // Photographer field JLabel photographerLabel = new JLabel( "Photographer" ); photographerField = new JTextField( 30 ); photographerDoc = photographerField.getDocument(); photographerDoc.addDocumentListener( this ); photographerDoc.putProperty( FIELD_NAME, PhotoInfoController.PHOTOGRAPHER ); // Shooting date field JLabel shootingDayLabel = new JLabel( "Shooting date" ); DateFormat df = DateFormat.getDateInstance(); DateFormatter shootingDayFormatter = new DateFormatter( df ); shootingDayField = new JFormattedTextField( df ); shootingDayField.setColumns( 10 ); shootingDayField.setValue( new Date( )); shootingDayField.addPropertyChangeListener( this ); shootingDayField.putClientProperty( FIELD_NAME, PhotoInfoController.SHOOTING_DATE ); // Shooting place field JLabel shootingPlaceLabel = new JLabel( "Shooting place" ); shootingPlaceField = new JTextField( 30 ); shootingPlaceDoc = shootingPlaceField.getDocument(); shootingPlaceDoc.addDocumentListener( this ); shootingPlaceDoc.putProperty( FIELD_NAME, PhotoInfoController.SHOOTING_PLACE ); // Description text JLabel descLabel = new JLabel( "Description" ); descriptionTextArea = new JTextArea( 5, 40 ); descriptionTextArea.setLineWrap( true ); descriptionTextArea.setWrapStyleWord( true ); JScrollPane descScrollPane = new JScrollPane( descriptionTextArea ); descScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); Border descBorder = BorderFactory.createEtchedBorder( EtchedBorder.LOWERED ); descBorder = BorderFactory.createTitledBorder( descBorder, "Description" ); descScrollPane.setBorder( descBorder ); descriptionDoc = descriptionTextArea.getDocument(); descriptionDoc.putProperty( FIELD_NAME, PhotoInfoController.DESCRIPTION ); descriptionDoc.addDocumentListener( this ); // Save button JButton saveBtn = new JButton( "Save" ); saveBtn.setActionCommand( "save" ); saveBtn.addActionListener( this ); // Discard button JButton discardBtn = new JButton( "Discard" ); discardBtn.setActionCommand( "discard" ); discardBtn.addActionListener( this ); // Lay out the created controls GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); generalPane.setLayout( layout ); JLabel[] labels = { photographerLabel, shootingDayLabel, shootingPlaceLabel }; JTextField[] fields = { photographerField, shootingDayField, shootingPlaceField }; addLabelTextRows( labels, fields, layout, generalPane ); generalPane.add( descScrollPane ); c.gridwidth = GridBagConstraints.REMAINDER; c.weighty = 0.5; c.fill = GridBagConstraints.NONE; layout.setConstraints( descScrollPane, c ); c = new GridBagConstraints(); c.gridwidth = 1; c.weighty = 0; c.fill = GridBagConstraints.NONE; c.gridy = GridBagConstraints.RELATIVE; generalPane.add( saveBtn ); layout.setConstraints( saveBtn, c ); c.gridy = GridBagConstraints.RELATIVE; generalPane.add( discardBtn ); layout.setConstraints( discardBtn, c ); createTechDataUI(); } |
generalPane.add( saveBtn ); layout.setConstraints( saveBtn, c ); | protected void createUI() { tabPane = new JTabbedPane(); add( tabPane ); // General pane JPanel generalPane = new JPanel(); tabPane.addTab( "General", generalPane ); // Create the fields & their labels // Photographer field JLabel photographerLabel = new JLabel( "Photographer" ); photographerField = new JTextField( 30 ); photographerDoc = photographerField.getDocument(); photographerDoc.addDocumentListener( this ); photographerDoc.putProperty( FIELD_NAME, PhotoInfoController.PHOTOGRAPHER ); // Shooting date field JLabel shootingDayLabel = new JLabel( "Shooting date" ); DateFormat df = DateFormat.getDateInstance(); DateFormatter shootingDayFormatter = new DateFormatter( df ); shootingDayField = new JFormattedTextField( df ); shootingDayField.setColumns( 10 ); shootingDayField.setValue( new Date( )); shootingDayField.addPropertyChangeListener( this ); shootingDayField.putClientProperty( FIELD_NAME, PhotoInfoController.SHOOTING_DATE ); // Shooting place field JLabel shootingPlaceLabel = new JLabel( "Shooting place" ); shootingPlaceField = new JTextField( 30 ); shootingPlaceDoc = shootingPlaceField.getDocument(); shootingPlaceDoc.addDocumentListener( this ); shootingPlaceDoc.putProperty( FIELD_NAME, PhotoInfoController.SHOOTING_PLACE ); // Description text JLabel descLabel = new JLabel( "Description" ); descriptionTextArea = new JTextArea( 5, 40 ); descriptionTextArea.setLineWrap( true ); descriptionTextArea.setWrapStyleWord( true ); JScrollPane descScrollPane = new JScrollPane( descriptionTextArea ); descScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); Border descBorder = BorderFactory.createEtchedBorder( EtchedBorder.LOWERED ); descBorder = BorderFactory.createTitledBorder( descBorder, "Description" ); descScrollPane.setBorder( descBorder ); descriptionDoc = descriptionTextArea.getDocument(); descriptionDoc.putProperty( FIELD_NAME, PhotoInfoController.DESCRIPTION ); descriptionDoc.addDocumentListener( this ); // Save button JButton saveBtn = new JButton( "Save" ); saveBtn.setActionCommand( "save" ); saveBtn.addActionListener( this ); // Discard button JButton discardBtn = new JButton( "Discard" ); discardBtn.setActionCommand( "discard" ); discardBtn.addActionListener( this ); // Lay out the created controls GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); generalPane.setLayout( layout ); JLabel[] labels = { photographerLabel, shootingDayLabel, shootingPlaceLabel }; JTextField[] fields = { photographerField, shootingDayField, shootingPlaceField }; addLabelTextRows( labels, fields, layout, generalPane ); generalPane.add( descScrollPane ); c.gridwidth = GridBagConstraints.REMAINDER; c.weighty = 0.5; c.fill = GridBagConstraints.NONE; layout.setConstraints( descScrollPane, c ); c = new GridBagConstraints(); c.gridwidth = 1; c.weighty = 0; c.fill = GridBagConstraints.NONE; c.gridy = GridBagConstraints.RELATIVE; generalPane.add( saveBtn ); layout.setConstraints( saveBtn, c ); c.gridy = GridBagConstraints.RELATIVE; generalPane.add( discardBtn ); layout.setConstraints( discardBtn, c ); createTechDataUI(); } |
|
generalPane.add( discardBtn ); layout.setConstraints( discardBtn, c ); | protected void createUI() { tabPane = new JTabbedPane(); add( tabPane ); // General pane JPanel generalPane = new JPanel(); tabPane.addTab( "General", generalPane ); // Create the fields & their labels // Photographer field JLabel photographerLabel = new JLabel( "Photographer" ); photographerField = new JTextField( 30 ); photographerDoc = photographerField.getDocument(); photographerDoc.addDocumentListener( this ); photographerDoc.putProperty( FIELD_NAME, PhotoInfoController.PHOTOGRAPHER ); // Shooting date field JLabel shootingDayLabel = new JLabel( "Shooting date" ); DateFormat df = DateFormat.getDateInstance(); DateFormatter shootingDayFormatter = new DateFormatter( df ); shootingDayField = new JFormattedTextField( df ); shootingDayField.setColumns( 10 ); shootingDayField.setValue( new Date( )); shootingDayField.addPropertyChangeListener( this ); shootingDayField.putClientProperty( FIELD_NAME, PhotoInfoController.SHOOTING_DATE ); // Shooting place field JLabel shootingPlaceLabel = new JLabel( "Shooting place" ); shootingPlaceField = new JTextField( 30 ); shootingPlaceDoc = shootingPlaceField.getDocument(); shootingPlaceDoc.addDocumentListener( this ); shootingPlaceDoc.putProperty( FIELD_NAME, PhotoInfoController.SHOOTING_PLACE ); // Description text JLabel descLabel = new JLabel( "Description" ); descriptionTextArea = new JTextArea( 5, 40 ); descriptionTextArea.setLineWrap( true ); descriptionTextArea.setWrapStyleWord( true ); JScrollPane descScrollPane = new JScrollPane( descriptionTextArea ); descScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); Border descBorder = BorderFactory.createEtchedBorder( EtchedBorder.LOWERED ); descBorder = BorderFactory.createTitledBorder( descBorder, "Description" ); descScrollPane.setBorder( descBorder ); descriptionDoc = descriptionTextArea.getDocument(); descriptionDoc.putProperty( FIELD_NAME, PhotoInfoController.DESCRIPTION ); descriptionDoc.addDocumentListener( this ); // Save button JButton saveBtn = new JButton( "Save" ); saveBtn.setActionCommand( "save" ); saveBtn.addActionListener( this ); // Discard button JButton discardBtn = new JButton( "Discard" ); discardBtn.setActionCommand( "discard" ); discardBtn.addActionListener( this ); // Lay out the created controls GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); generalPane.setLayout( layout ); JLabel[] labels = { photographerLabel, shootingDayLabel, shootingPlaceLabel }; JTextField[] fields = { photographerField, shootingDayField, shootingPlaceField }; addLabelTextRows( labels, fields, layout, generalPane ); generalPane.add( descScrollPane ); c.gridwidth = GridBagConstraints.REMAINDER; c.weighty = 0.5; c.fill = GridBagConstraints.NONE; layout.setConstraints( descScrollPane, c ); c = new GridBagConstraints(); c.gridwidth = 1; c.weighty = 0; c.fill = GridBagConstraints.NONE; c.gridy = GridBagConstraints.RELATIVE; generalPane.add( saveBtn ); layout.setConstraints( saveBtn, c ); c.gridy = GridBagConstraints.RELATIVE; generalPane.add( discardBtn ); layout.setConstraints( discardBtn, c ); createTechDataUI(); } |
|
JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(discardBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(saveBtn); add( buttonPane, BorderLayout.SOUTH ); | protected void createUI() { tabPane = new JTabbedPane(); add( tabPane ); // General pane JPanel generalPane = new JPanel(); tabPane.addTab( "General", generalPane ); // Create the fields & their labels // Photographer field JLabel photographerLabel = new JLabel( "Photographer" ); photographerField = new JTextField( 30 ); photographerDoc = photographerField.getDocument(); photographerDoc.addDocumentListener( this ); photographerDoc.putProperty( FIELD_NAME, PhotoInfoController.PHOTOGRAPHER ); // Shooting date field JLabel shootingDayLabel = new JLabel( "Shooting date" ); DateFormat df = DateFormat.getDateInstance(); DateFormatter shootingDayFormatter = new DateFormatter( df ); shootingDayField = new JFormattedTextField( df ); shootingDayField.setColumns( 10 ); shootingDayField.setValue( new Date( )); shootingDayField.addPropertyChangeListener( this ); shootingDayField.putClientProperty( FIELD_NAME, PhotoInfoController.SHOOTING_DATE ); // Shooting place field JLabel shootingPlaceLabel = new JLabel( "Shooting place" ); shootingPlaceField = new JTextField( 30 ); shootingPlaceDoc = shootingPlaceField.getDocument(); shootingPlaceDoc.addDocumentListener( this ); shootingPlaceDoc.putProperty( FIELD_NAME, PhotoInfoController.SHOOTING_PLACE ); // Description text JLabel descLabel = new JLabel( "Description" ); descriptionTextArea = new JTextArea( 5, 40 ); descriptionTextArea.setLineWrap( true ); descriptionTextArea.setWrapStyleWord( true ); JScrollPane descScrollPane = new JScrollPane( descriptionTextArea ); descScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); Border descBorder = BorderFactory.createEtchedBorder( EtchedBorder.LOWERED ); descBorder = BorderFactory.createTitledBorder( descBorder, "Description" ); descScrollPane.setBorder( descBorder ); descriptionDoc = descriptionTextArea.getDocument(); descriptionDoc.putProperty( FIELD_NAME, PhotoInfoController.DESCRIPTION ); descriptionDoc.addDocumentListener( this ); // Save button JButton saveBtn = new JButton( "Save" ); saveBtn.setActionCommand( "save" ); saveBtn.addActionListener( this ); // Discard button JButton discardBtn = new JButton( "Discard" ); discardBtn.setActionCommand( "discard" ); discardBtn.addActionListener( this ); // Lay out the created controls GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); generalPane.setLayout( layout ); JLabel[] labels = { photographerLabel, shootingDayLabel, shootingPlaceLabel }; JTextField[] fields = { photographerField, shootingDayField, shootingPlaceField }; addLabelTextRows( labels, fields, layout, generalPane ); generalPane.add( descScrollPane ); c.gridwidth = GridBagConstraints.REMAINDER; c.weighty = 0.5; c.fill = GridBagConstraints.NONE; layout.setConstraints( descScrollPane, c ); c = new GridBagConstraints(); c.gridwidth = 1; c.weighty = 0; c.fill = GridBagConstraints.NONE; c.gridy = GridBagConstraints.RELATIVE; generalPane.add( saveBtn ); layout.setConstraints( saveBtn, c ); c.gridy = GridBagConstraints.RELATIVE; generalPane.add( discardBtn ); layout.setConstraints( discardBtn, c ); createTechDataUI(); } |
|
if ( project.getTaskDefinitions().containsKey( tagName ) ) { if(tagName.equals(ANT_MANIFEST_TAG)) { TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { Object nested = null; Object parentObject = null; | TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { parentObject = ancestor.getTaskObject(); } | public void doTag(XMLOutput output) throws Exception { Project project = getAntProject(); String tagName = getTagName(); if ( project.getTaskDefinitions().containsKey( tagName ) ) { // check if manifest is contained within a jar // special handling for Ant 1.5 manifest which is a task // but can also be contained within the jar task // There has got to be a better way but I couldn't find it if(tagName.equals(ANT_MANIFEST_TAG)) { TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { Object nested = null; Object parentObject = null; parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } return; } } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference task = createTask( tagName ); if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { String text = getBodyText(); Object[] args = { text }; method.invoke(this.task, args); } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } else { Object nested = null; Object parentObject = null; // must be a datatype. TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); } if ( nested == null ) { nested = createDataType( tagName ); } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } } } |
parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); String body = getBodyText(); setBeanProperties(); if ( parentObject != null) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { } } return; } | if ( ! ( parentObject instanceof Task ) && project.getTaskDefinitions().containsKey( tagName ) ) { if ( log.isDebugEnabled() ) { log.debug( "Creating an ant Task for name: " + tagName ); | public void doTag(XMLOutput output) throws Exception { Project project = getAntProject(); String tagName = getTagName(); if ( project.getTaskDefinitions().containsKey( tagName ) ) { // check if manifest is contained within a jar // special handling for Ant 1.5 manifest which is a task // but can also be contained within the jar task // There has got to be a better way but I couldn't find it if(tagName.equals(ANT_MANIFEST_TAG)) { TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { Object nested = null; Object parentObject = null; parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } return; } } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference task = createTask( tagName ); if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { String text = getBodyText(); Object[] args = { text }; method.invoke(this.task, args); } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } else { Object nested = null; Object parentObject = null; // must be a datatype. TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); } if ( nested == null ) { nested = createDataType( tagName ); } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } } } |
else { Object nested = null; Object parentObject = null; | else { | public void doTag(XMLOutput output) throws Exception { Project project = getAntProject(); String tagName = getTagName(); if ( project.getTaskDefinitions().containsKey( tagName ) ) { // check if manifest is contained within a jar // special handling for Ant 1.5 manifest which is a task // but can also be contained within the jar task // There has got to be a better way but I couldn't find it if(tagName.equals(ANT_MANIFEST_TAG)) { TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { Object nested = null; Object parentObject = null; parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } return; } } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference task = createTask( tagName ); if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { String text = getBodyText(); Object[] args = { text }; method.invoke(this.task, args); } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } else { Object nested = null; Object parentObject = null; // must be a datatype. TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); } if ( nested == null ) { nested = createDataType( tagName ); } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } } } |
TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); | if ( log.isDebugEnabled() ) { log.debug( "Creating a nested object name: " + tagName ); | public void doTag(XMLOutput output) throws Exception { Project project = getAntProject(); String tagName = getTagName(); if ( project.getTaskDefinitions().containsKey( tagName ) ) { // check if manifest is contained within a jar // special handling for Ant 1.5 manifest which is a task // but can also be contained within the jar task // There has got to be a better way but I couldn't find it if(tagName.equals(ANT_MANIFEST_TAG)) { TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { Object nested = null; Object parentObject = null; parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } return; } } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference task = createTask( tagName ); if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { String text = getBodyText(); Object[] args = { text }; method.invoke(this.task, args); } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } else { Object nested = null; Object parentObject = null; // must be a datatype. TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); } if ( nested == null ) { nested = createDataType( tagName ); } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } } } |
Object nested = createNestedObject( parentObject, tagName ); | public void doTag(XMLOutput output) throws Exception { Project project = getAntProject(); String tagName = getTagName(); if ( project.getTaskDefinitions().containsKey( tagName ) ) { // check if manifest is contained within a jar // special handling for Ant 1.5 manifest which is a task // but can also be contained within the jar task // There has got to be a better way but I couldn't find it if(tagName.equals(ANT_MANIFEST_TAG)) { TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { Object nested = null; Object parentObject = null; parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } return; } } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference task = createTask( tagName ); if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { String text = getBodyText(); Object[] args = { text }; method.invoke(this.task, args); } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } else { Object nested = null; Object parentObject = null; // must be a datatype. TaskSource ancestor = (TaskSource) findAncestorWithClass( TaskSource.class ); if ( ancestor != null ) { parentObject = ancestor.getTaskObject(); nested = createNestedObject( parentObject, tagName ); } if ( nested == null ) { nested = createDataType( tagName ); } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { //log.warn( "Caught exception setting nested: " + tagName, e ); } } } } |
|
assertEquals("fully qualified attributes not passed", "<html xmlns=\"http: data); | public void testSimpleFileTag() throws Exception { setUpScript("testFileTag.jelly"); Script script = getJelly().compileScript(); script.run(getJellyContext(), getXMLOutput()); String data = (String)getJellyContext().getVariable("testFileTag"); //FIXME This doesn't take into account attribute ordering //assertEquals("target/testFileTag.tmp", // "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"></html>", // data); } |
|
setTag(tag); | public void run(JellyContext context, XMLOutput output) throws Exception { startNamespacePrefixes(output); Tag tag = getTag(); // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); try { if ( tag == null ) { return; } tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyException e) { handleException(e); } catch (Exception e) { handleException(e); } endNamespacePrefixes(output); } |
|
Options.setMissingThreshold(0.4); | Options.setMissingThreshold(1.0); | public HaploView(){ Options.setMissingThreshold(0.4); try{ fc = new JFileChooser(System.getProperty("user.dir")); }catch(NullPointerException n){ try{ UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); fc = new JFileChooser(System.getProperty("user.dir")); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e){ } } //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); analysisItem = new JMenuItem(READ_ANALYSIS_TRACK); setAccelerator(analysisItem, 'A', false); analysisItem.addActionListener(this); analysisItem.setEnabled(false); fileMenu.add(analysisItem); blocksItem = new JMenuItem(READ_BLOCKS_FILE); setAccelerator(blocksItem, 'B', false); blocksItem.addActionListener(this); blocksItem.setEnabled(false); fileMenu.add(blocksItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); fileMenu.setMnemonic(KeyEvent.VK_F); menuItem = new JMenuItem("Quit"); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); displayMenu.setMnemonic(KeyEvent.VK_D); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); viewMenuItems[i].setEnabled(false); group.add(viewMenuItems[i]); } displayMenu.addSeparator(); //a submenu ButtonGroup zg = new ButtonGroup(); JMenu zoomMenu = new JMenu("LD zoom"); zoomMenu.setMnemonic(KeyEvent.VK_Z); zoomMenuItems = new JRadioButtonMenuItem[zoomItems.length]; for (int i = 0; i < zoomItems.length; i++){ zoomMenuItems[i] = new JRadioButtonMenuItem(zoomItems[i], i==0); zoomMenuItems[i].addActionListener(this); zoomMenuItems[i].setActionCommand("zoom" + i); zoomMenu.add(zoomMenuItems[i]); zg.add(zoomMenuItems[i]); } displayMenu.add(zoomMenu); //another submenu ButtonGroup cg = new ButtonGroup(); JMenu colorMenu = new JMenu("LD color scheme"); colorMenu.setMnemonic(KeyEvent.VK_C); colorMenuItems = new JRadioButtonMenuItem[colorItems.length]; for (int i = 0; i< colorItems.length; i++){ colorMenuItems[i] = new JRadioButtonMenuItem(colorItems[i],i==0); colorMenuItems[i].addActionListener(this); colorMenuItems[i].setActionCommand("color" + i); colorMenu.add(colorMenuItems[i]); cg.add(colorMenuItems[i]); } displayMenu.add(colorMenu); //analysis menu JMenu analysisMenu = new JMenu("Analysis"); analysisMenu.setMnemonic(KeyEvent.VK_A); menuBar.add(analysisMenu); //a submenu ButtonGroup bg = new ButtonGroup(); JMenu blockMenu = new JMenu("Define Blocks"); blockMenu.setMnemonic(KeyEvent.VK_B); blockMenuItems = new JRadioButtonMenuItem[blockItems.length]; for (int i = 0; i < blockItems.length; i++){ blockMenuItems[i] = new JRadioButtonMenuItem(blockItems[i], i==0); blockMenuItems[i].addActionListener(this); blockMenuItems[i].setActionCommand("block" + i); blockMenuItems[i].setEnabled(false); blockMenu.add(blockMenuItems[i]); bg.add(blockMenuItems[i]); } analysisMenu.add(blockMenu); clearBlocksItem = new JMenuItem(CLEAR_BLOCKS); setAccelerator(clearBlocksItem, 'C', false); clearBlocksItem.addActionListener(this); clearBlocksItem.setEnabled(false); analysisMenu.add(clearBlocksItem); JMenuItem customizeBlocksItem = new JMenuItem(CUST_BLOCKS); customizeBlocksItem.addActionListener(this); analysisMenu.add(customizeBlocksItem); //color key keyMenu = new JMenu("Key"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(keyMenu); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
theData = new HaploData(assocTest); | theData = new HaploData(); | void readGenotypes(String[] inputOptions, int type){ //input is a 3 element array with //inputOptions[0] = ped file //inputOptions[1] = info file ("" if none) //inputOptions[2] = max comparison distance (don't compute d' if markers are greater than this dist apart) //type is either 3 or 4 for ped and hapmap files respectively final File inFile = new File(inputOptions[0]); //deal with max comparison distance if (inputOptions[2].equals("")){ inputOptions[2] = "0"; } maxCompDist = Long.parseLong(inputOptions[2])*1000; try { if (inFile.length() < 1){ throw new HaploViewException("Genotype file is empty or nonexistent: " + inFile.getName()); } if (type == HAPS){ //these are not available for non ped files viewMenuItems[VIEW_CHECK_NUM].setEnabled(false); viewMenuItems[VIEW_TDT_NUM].setEnabled(false); assocTest = 0; } theData = new HaploData(assocTest); if (type == HAPS){ theData.prepareHapsInput(new File(inputOptions[0])); }else{ theData.linkageToChrom(inFile, type); } //deal with marker information theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } checkPanel = null; if (type == HAPS){ readMarkers(markerFile, null); }else{ readMarkers(markerFile, theData.getPedFile().getHMInfo()); checkPanel = new CheckDataPanel(theData, true); checkPanel.setAlignmentX(Component.CENTER_ALIGNMENT); } //let's start the math this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final SwingWorker worker = new SwingWorker(){ public Object construct(){ dPrimeDisplay=null; changeKey(1); theData.generateDPrimeTable(); theData.guessBlocks(BLOX_GABRIEL); //theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(window); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inFile.getName()); return null; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (theData.finished){ timer.stop(); for (int i = 0; i < blockMenuItems.length; i++){ blockMenuItems[i].setEnabled(true); } clearBlocksItem.setEnabled(true); readMarkerItem.setEnabled(true); blocksItem.setEnabled(true); exportMenuItems[2].setEnabled(true); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }); worker.start(); timer.start(); }catch(IOException ioexec) { JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } catch(PedFileException pfe){ JOptionPane.showMessageDialog(this, pfe.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (HaploViewException hve){ JOptionPane.showMessageDialog(this, hve.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } } |
tdtPanel = new TDTPanel(theData.chromosomes, assocTest); | tdtPanel = new TDTPanel(theData.getPedFile(), assocTest); | void readGenotypes(String[] inputOptions, int type){ //input is a 3 element array with //inputOptions[0] = ped file //inputOptions[1] = info file ("" if none) //inputOptions[2] = max comparison distance (don't compute d' if markers are greater than this dist apart) //type is either 3 or 4 for ped and hapmap files respectively final File inFile = new File(inputOptions[0]); //deal with max comparison distance if (inputOptions[2].equals("")){ inputOptions[2] = "0"; } maxCompDist = Long.parseLong(inputOptions[2])*1000; try { if (inFile.length() < 1){ throw new HaploViewException("Genotype file is empty or nonexistent: " + inFile.getName()); } if (type == HAPS){ //these are not available for non ped files viewMenuItems[VIEW_CHECK_NUM].setEnabled(false); viewMenuItems[VIEW_TDT_NUM].setEnabled(false); assocTest = 0; } theData = new HaploData(assocTest); if (type == HAPS){ theData.prepareHapsInput(new File(inputOptions[0])); }else{ theData.linkageToChrom(inFile, type); } //deal with marker information theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } checkPanel = null; if (type == HAPS){ readMarkers(markerFile, null); }else{ readMarkers(markerFile, theData.getPedFile().getHMInfo()); checkPanel = new CheckDataPanel(theData, true); checkPanel.setAlignmentX(Component.CENTER_ALIGNMENT); } //let's start the math this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final SwingWorker worker = new SwingWorker(){ public Object construct(){ dPrimeDisplay=null; changeKey(1); theData.generateDPrimeTable(); theData.guessBlocks(BLOX_GABRIEL); //theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(window); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inFile.getName()); return null; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (theData.finished){ timer.stop(); for (int i = 0; i < blockMenuItems.length; i++){ blockMenuItems[i].setEnabled(true); } clearBlocksItem.setEnabled(true); readMarkerItem.setEnabled(true); blocksItem.setEnabled(true); exportMenuItems[2].setEnabled(true); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }); worker.start(); timer.start(); }catch(IOException ioexec) { JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } catch(PedFileException pfe){ JOptionPane.showMessageDialog(this, pfe.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (HaploViewException hve){ JOptionPane.showMessageDialog(this, hve.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } } |
tdtPanel = new TDTPanel(theData.chromosomes, assocTest); | tdtPanel = new TDTPanel(theData.getPedFile(), assocTest); | public Object construct(){ dPrimeDisplay=null; changeKey(1); theData.generateDPrimeTable(); theData.guessBlocks(BLOX_GABRIEL); //theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(window); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inFile.getName()); return null; } |
if(usedParents.contains(mom) || usedParents.contains(dad)) { continue; } | private void buildParenTDTTrioSet(PedFile pf, Vector permuteInd, TreeSet snpsToBeTested) throws PedFileException{ Vector results = new Vector(); Vector indList = pf.getAllIndividuals(); if(permuteInd == null || permuteInd.size() != indList.size()) { permuteInd = new Vector(); for (int i = 0; i < indList.size(); i++){ permuteInd.add(new Boolean(false)); } } //todo: need to make sure each set of parents only used once int numMarkers = Chromosome.getUnfilteredSize(); for (int i = 0; i < numMarkers; i++){ SNP currentMarker = Chromosome.getUnfilteredMarker(i); if (snpsToBeTested.contains(currentMarker)){ int discordantNotTallied=0; int discordantTallied = 0; Individual currentInd; Family currentFam; HashSet usedParents = new HashSet(); AssociationResult.TallyTrio tt = new AssociationResult.TallyTrio(); for (int j = 0; j < indList.size(); j++){ currentInd = (Individual)indList.elementAt(j); currentFam = pf.getFamily(currentInd.getFamilyID()); if (currentFam.containsMember(currentInd.getMomID()) && currentFam.containsMember(currentInd.getDadID()) && currentInd.getAffectedStatus() == 2){ //if he has both parents, and is affected, we can get a transmission Individual mom = currentFam.getMember(currentInd.getMomID()); Individual dad = currentFam.getMember(currentInd.getDadID()); if(usedParents.contains(mom) || usedParents.contains(dad)) { continue; } if(currentInd.getZeroed(i) || dad.getZeroed(i) || mom.getZeroed(i)) { continue; } byte kid1 = currentInd.getMarkerA(i); byte kid2 = currentInd.getMarkerB(i); byte dad1 = dad.getMarkerA(i); byte dad2 = dad.getMarkerB(i); byte mom1 = mom.getMarkerA(i); byte mom2 = mom.getMarkerB(i); byte momT=0, momU=0, dadT=0, dadU=0; if (kid1 == 0 || kid2 == 0 || dad1 == 0 || dad2 == 0 || mom1 == 0 || mom2 == 0) { continue; } else if (kid1 == kid2) { //kid homozygous if (dad1 == kid1) { dadT = dad1; dadU = dad2; } else { dadT = dad2; dadU = dad1; } if (mom1 == kid1) { momT = mom1; momU = mom2; } else { momT = mom2; momU = mom1; } } else { if (dad1 == dad2 && mom1 != mom2) { //dad hom mom het dadT = dad1; dadU = dad2; if (kid1 == dad1) { momT = kid2; momU = kid1; } else { momT = kid1; momU = kid2; } } else if (mom1 == mom2 && dad1 != dad2) { //dad het mom hom momT = mom1; momU = mom2; if (kid1 == mom1) { dadT = kid2; dadU = kid1; } else { dadT = kid1; dadU = kid2; } } else if (dad1 == dad2 && mom1 == mom2) { //mom & dad hom dadT = dad1; dadU = dad1; momT = mom1; momU = mom1; } else { //everybody het dadT = (byte)(4+dad1); dadU = (byte)(4+dad2); momT = (byte)(4+mom1); momU = (byte)(4+mom2); } } if(((Boolean)permuteInd.get(j)).booleanValue()) { tt.tallyTrioInd(dadU, dadT); tt.tallyTrioInd(momU, momT); } else { tt.tallyTrioInd(dadT, dadU); tt.tallyTrioInd(momT, momU); } if(mom.getAffectedStatus() != dad.getAffectedStatus()) { //discordant parental phenotypes if(!(dad1 == mom1 && dad2 == mom2) && !(dad1 == mom2 && dad2 == mom1)) { if(mom.getAffectedStatus() == 2) { tt.tallyDiscordantParents(momT,momU,dadT,dadU); } else if(dad.getAffectedStatus() == 2) { tt.tallyDiscordantParents(dadT,dadU,momT,momU); } discordantTallied++; }else { discordantNotTallied++; } } usedParents.add(mom); usedParents.add(dad); } } int[] g1 = {tt.allele1}; int[] g2 = {tt.allele2}; int[] m = {i}; Haplotype thisSNP1 = new Haplotype(g1, 0, m, null); thisSNP1.setTransCount(tt.counts[0][0]); thisSNP1.setUntransCount(tt.counts[1][0]); thisSNP1.setDiscordantAlleleCounts(tt.discordantAlleleCounts); Haplotype thisSNP2 = new Haplotype(g2, 0, m, null); thisSNP2.setTransCount(tt.counts[0][1]); thisSNP2.setUntransCount(tt.counts[1][1]); thisSNP2.setDiscordantAlleleCounts(tt.getDiscordantCountsAllele2()); Haplotype[] daBlock = {thisSNP1, thisSNP2}; results.add(new MarkerAssociationResult(daBlock, currentMarker.getName(), currentMarker)); } } this.results = results; } |
|
if(usedParents.contains(mom) || usedParents.contains(dad)) { continue; } | private void buildParenTDTTrioSet(PedFile pf, Vector permuteInd, TreeSet snpsToBeTested) throws PedFileException{ Vector results = new Vector(); Vector indList = pf.getAllIndividuals(); if(permuteInd == null || permuteInd.size() != indList.size()) { permuteInd = new Vector(); for (int i = 0; i < indList.size(); i++){ permuteInd.add(new Boolean(false)); } } //todo: need to make sure each set of parents only used once int numMarkers = Chromosome.getUnfilteredSize(); for (int i = 0; i < numMarkers; i++){ SNP currentMarker = Chromosome.getUnfilteredMarker(i); if (snpsToBeTested.contains(currentMarker)){ int discordantNotTallied=0; int discordantTallied = 0; Individual currentInd; Family currentFam; HashSet usedParents = new HashSet(); AssociationResult.TallyTrio tt = new AssociationResult.TallyTrio(); for (int j = 0; j < indList.size(); j++){ currentInd = (Individual)indList.elementAt(j); currentFam = pf.getFamily(currentInd.getFamilyID()); if (currentFam.containsMember(currentInd.getMomID()) && currentFam.containsMember(currentInd.getDadID()) && currentInd.getAffectedStatus() == 2){ //if he has both parents, and is affected, we can get a transmission Individual mom = currentFam.getMember(currentInd.getMomID()); Individual dad = currentFam.getMember(currentInd.getDadID()); if(usedParents.contains(mom) || usedParents.contains(dad)) { continue; } if(currentInd.getZeroed(i) || dad.getZeroed(i) || mom.getZeroed(i)) { continue; } byte kid1 = currentInd.getMarkerA(i); byte kid2 = currentInd.getMarkerB(i); byte dad1 = dad.getMarkerA(i); byte dad2 = dad.getMarkerB(i); byte mom1 = mom.getMarkerA(i); byte mom2 = mom.getMarkerB(i); byte momT=0, momU=0, dadT=0, dadU=0; if (kid1 == 0 || kid2 == 0 || dad1 == 0 || dad2 == 0 || mom1 == 0 || mom2 == 0) { continue; } else if (kid1 == kid2) { //kid homozygous if (dad1 == kid1) { dadT = dad1; dadU = dad2; } else { dadT = dad2; dadU = dad1; } if (mom1 == kid1) { momT = mom1; momU = mom2; } else { momT = mom2; momU = mom1; } } else { if (dad1 == dad2 && mom1 != mom2) { //dad hom mom het dadT = dad1; dadU = dad2; if (kid1 == dad1) { momT = kid2; momU = kid1; } else { momT = kid1; momU = kid2; } } else if (mom1 == mom2 && dad1 != dad2) { //dad het mom hom momT = mom1; momU = mom2; if (kid1 == mom1) { dadT = kid2; dadU = kid1; } else { dadT = kid1; dadU = kid2; } } else if (dad1 == dad2 && mom1 == mom2) { //mom & dad hom dadT = dad1; dadU = dad1; momT = mom1; momU = mom1; } else { //everybody het dadT = (byte)(4+dad1); dadU = (byte)(4+dad2); momT = (byte)(4+mom1); momU = (byte)(4+mom2); } } if(((Boolean)permuteInd.get(j)).booleanValue()) { tt.tallyTrioInd(dadU, dadT); tt.tallyTrioInd(momU, momT); } else { tt.tallyTrioInd(dadT, dadU); tt.tallyTrioInd(momT, momU); } if(mom.getAffectedStatus() != dad.getAffectedStatus()) { //discordant parental phenotypes if(!(dad1 == mom1 && dad2 == mom2) && !(dad1 == mom2 && dad2 == mom1)) { if(mom.getAffectedStatus() == 2) { tt.tallyDiscordantParents(momT,momU,dadT,dadU); } else if(dad.getAffectedStatus() == 2) { tt.tallyDiscordantParents(dadT,dadU,momT,momU); } discordantTallied++; }else { discordantNotTallied++; } } usedParents.add(mom); usedParents.add(dad); } } int[] g1 = {tt.allele1}; int[] g2 = {tt.allele2}; int[] m = {i}; Haplotype thisSNP1 = new Haplotype(g1, 0, m, null); thisSNP1.setTransCount(tt.counts[0][0]); thisSNP1.setUntransCount(tt.counts[1][0]); thisSNP1.setDiscordantAlleleCounts(tt.discordantAlleleCounts); Haplotype thisSNP2 = new Haplotype(g2, 0, m, null); thisSNP2.setTransCount(tt.counts[0][1]); thisSNP2.setUntransCount(tt.counts[1][1]); thisSNP2.setDiscordantAlleleCounts(tt.getDiscordantCountsAllele2()); Haplotype[] daBlock = {thisSNP1, thisSNP2}; results.add(new MarkerAssociationResult(daBlock, currentMarker.getName(), currentMarker)); } } this.results = results; } |
|
Haplotype h = (Haplotype) alleles.get(i); | Haplotype h = (Haplotype) filteredAlleles.get(i); | public String getCountString(int i){ nf.setMinimumFractionDigits(1); nf.setMaximumFractionDigits(1); Haplotype h = (Haplotype) alleles.get(i); StringBuffer countSB = new StringBuffer(); if(Options.getAssocTest() == ASSOC_TRIO) { countSB.append(nf.format(h.getTransCount())).append(" : ").append(nf.format(h.getUntransCount())); } else if(Options.getAssocTest() == ASSOC_CC) { double caseSum = 0, controlSum = 0; for (int j = 0; j < alleles.size(); j++){ if (i!=j){ caseSum += ((Haplotype)alleles.get(j)).getCaseCount(); controlSum += ((Haplotype)alleles.get(j)).getControlCount(); } } countSB.append(nf.format(h.getCaseCount())).append(" : ").append(nf.format(caseSum)).append(", "); countSB.append(nf.format(h.getControlCount())).append(" : ").append(nf.format(controlSum)); } return countSB.toString(); } |
public String getPValue(int i) { | public Double getPValue(int i) { | public String getPValue(int i) { if (pValues == null || i >= pValues.size()){ return ""; } return Util.formatPValue(((Double)pValues.get(i)).doubleValue()); } |
return ""; | return new Double(0); | public String getPValue(int i) { if (pValues == null || i >= pValues.size()){ return ""; } return Util.formatPValue(((Double)pValues.get(i)).doubleValue()); } |
return Util.formatPValue(((Double)pValues.get(i)).doubleValue()); | return new Double(Util.formatPValue(((Double)pValues.get(i)).doubleValue())); | public String getPValue(int i) { if (pValues == null || i >= pValues.size()){ return ""; } return Util.formatPValue(((Double)pValues.get(i)).doubleValue()); } |
long mDistance = Long.parseLong(st.nextToken()); | double mDistance = Double.parseDouble(st.nextToken()); | public void parseWGA(String wga, String map, boolean embed) throws PlinkException { markers = new Vector(); results = new Vector(); columns = new Vector(); columns.add("Result"); columns.add("Chrom"); columns.add("Marker"); columns.add("Position"); final File wgaFile = new File(wga); final File mapFile = new File(map); Hashtable markerHash = new Hashtable(1,1); Vector ignoredMarkers = new Vector(); try{ if (wgaFile.length() < 1){ throw new PlinkException("plink file is empty or nonexistent."); } if (!embed){ if (mapFile.length() < 1){ throw new PlinkException("Map file is empty or nonexistent."); } BufferedReader mapReader = new BufferedReader(new FileReader(mapFile)); String mapLine; String unknownChrom = "0"; while((mapLine = mapReader.readLine())!=null) { if (mapLine.length() == 0){ //skip blank lines continue; } StringTokenizer st = new StringTokenizer(mapLine,"\t "); String chrom = st.nextToken(); String chr; if (chrom.equals("0")){ chr = unknownChrom; }else if (chrom.equalsIgnoreCase("x") || chrom.equalsIgnoreCase("xy")){ chr = CHROM_NAMES[22]; } else{ chr = CHROM_NAMES[Integer.parseInt(chrom)-1]; } String marker = new String(st.nextToken()); long mDistance = Long.parseLong(st.nextToken()); long position = Long.parseLong(st.nextToken()); Marker mark = new Marker(chr, marker, mDistance, position); markers.add(mark); markerHash.put(mark.getMarkerID(), mark); } } BufferedReader wgaReader = new BufferedReader(new FileReader(wgaFile)); int numColumns = 0; int markerColumn = -1; int chromColumn = -1; int positionColumn = -1; int morganColumn = -1; String headerLine = wgaReader.readLine(); StringTokenizer headerSt = new StringTokenizer(headerLine); while (headerSt.hasMoreTokens()){ String column = new String(headerSt.nextToken()); if (column.equals("SNP")){ markerColumn = numColumns; numColumns++; }else if (column.equals("CHR")){ chromColumn = numColumns; numColumns++; }else if (column.equals("POS")){ positionColumn = numColumns; numColumns++; }else if (column.equals("MORGAN")){ morganColumn = numColumns; numColumns++; } else{ columns.add(column); numColumns++; } } if (markerColumn == -1){ throw new PlinkException("Results file must contain a SNP column."); } if (embed){ if (chromColumn == -1 || positionColumn == -1 || morganColumn == -1){ throw new PlinkException("Results files with embedded map files must contain CHR, POS, and MORGAN columns."); } } String wgaLine; int lineNumber = 0; while((wgaLine = wgaReader.readLine())!=null){ if (wgaLine.length() == 0){ //skip blank lines continue; } int tokenNumber = 0; //StringTokenizer tokenizer = new StringTokenizer(wgaLine,"\t :"); StringTokenizer tokenizer = new StringTokenizer(wgaLine); String marker = null; String chromosome = null; long position = 0; long morganDistance = 0; Vector values = new Vector(); while(tokenizer.hasMoreTokens()){ if (tokenNumber == markerColumn){ marker = new String(tokenizer.nextToken()); }else if (tokenNumber == chromColumn){ chromosome = new String(tokenizer.nextToken()); if(chromosome.equals("23")){ chromosome = "X"; } }else if (tokenNumber == positionColumn){ position = (new Long(new String(tokenizer.nextToken()))).longValue(); }else if (tokenNumber == morganColumn){ morganDistance = (new Long(new String(tokenizer.nextToken()))).longValue(); } else{ values.add(new String(tokenizer.nextToken())); } tokenNumber++; } if (tokenNumber != numColumns){ throw new PlinkException("Inconsistent column number on line " + (lineNumber+1)); } Marker assocMarker; if (!embed){ assocMarker = (Marker)markerHash.get(marker); if (assocMarker == null){ ignoredMarkers.add(marker); lineNumber++; continue; }else if (!(assocMarker.getChromosome().equalsIgnoreCase(chromosome)) && chromosome != null){ throw new PlinkException("Incompatible chromsomes."); } }else{ assocMarker = new Marker(chromosome,marker,morganDistance,position); } AssociationResult result = new AssociationResult(lineNumber,assocMarker,values); results.add(result); lineNumber++; } }catch(IOException ioe){ throw new PlinkException("File error."); }catch(NumberFormatException nfe){ throw new PlinkException("File formatting error."); } if (ignoredMarkers.size() != 0){ IgnoredMarkersDialog imd = new IgnoredMarkersDialog(hv,"Ignored Markers",ignoredMarkers,false); imd.pack(); imd.setVisible(true); } hv.setPlinkData(results,columns); } |
long morganDistance = 0; | double morganDistance = 0; | public void parseWGA(String wga, String map, boolean embed) throws PlinkException { markers = new Vector(); results = new Vector(); columns = new Vector(); columns.add("Result"); columns.add("Chrom"); columns.add("Marker"); columns.add("Position"); final File wgaFile = new File(wga); final File mapFile = new File(map); Hashtable markerHash = new Hashtable(1,1); Vector ignoredMarkers = new Vector(); try{ if (wgaFile.length() < 1){ throw new PlinkException("plink file is empty or nonexistent."); } if (!embed){ if (mapFile.length() < 1){ throw new PlinkException("Map file is empty or nonexistent."); } BufferedReader mapReader = new BufferedReader(new FileReader(mapFile)); String mapLine; String unknownChrom = "0"; while((mapLine = mapReader.readLine())!=null) { if (mapLine.length() == 0){ //skip blank lines continue; } StringTokenizer st = new StringTokenizer(mapLine,"\t "); String chrom = st.nextToken(); String chr; if (chrom.equals("0")){ chr = unknownChrom; }else if (chrom.equalsIgnoreCase("x") || chrom.equalsIgnoreCase("xy")){ chr = CHROM_NAMES[22]; } else{ chr = CHROM_NAMES[Integer.parseInt(chrom)-1]; } String marker = new String(st.nextToken()); long mDistance = Long.parseLong(st.nextToken()); long position = Long.parseLong(st.nextToken()); Marker mark = new Marker(chr, marker, mDistance, position); markers.add(mark); markerHash.put(mark.getMarkerID(), mark); } } BufferedReader wgaReader = new BufferedReader(new FileReader(wgaFile)); int numColumns = 0; int markerColumn = -1; int chromColumn = -1; int positionColumn = -1; int morganColumn = -1; String headerLine = wgaReader.readLine(); StringTokenizer headerSt = new StringTokenizer(headerLine); while (headerSt.hasMoreTokens()){ String column = new String(headerSt.nextToken()); if (column.equals("SNP")){ markerColumn = numColumns; numColumns++; }else if (column.equals("CHR")){ chromColumn = numColumns; numColumns++; }else if (column.equals("POS")){ positionColumn = numColumns; numColumns++; }else if (column.equals("MORGAN")){ morganColumn = numColumns; numColumns++; } else{ columns.add(column); numColumns++; } } if (markerColumn == -1){ throw new PlinkException("Results file must contain a SNP column."); } if (embed){ if (chromColumn == -1 || positionColumn == -1 || morganColumn == -1){ throw new PlinkException("Results files with embedded map files must contain CHR, POS, and MORGAN columns."); } } String wgaLine; int lineNumber = 0; while((wgaLine = wgaReader.readLine())!=null){ if (wgaLine.length() == 0){ //skip blank lines continue; } int tokenNumber = 0; //StringTokenizer tokenizer = new StringTokenizer(wgaLine,"\t :"); StringTokenizer tokenizer = new StringTokenizer(wgaLine); String marker = null; String chromosome = null; long position = 0; long morganDistance = 0; Vector values = new Vector(); while(tokenizer.hasMoreTokens()){ if (tokenNumber == markerColumn){ marker = new String(tokenizer.nextToken()); }else if (tokenNumber == chromColumn){ chromosome = new String(tokenizer.nextToken()); if(chromosome.equals("23")){ chromosome = "X"; } }else if (tokenNumber == positionColumn){ position = (new Long(new String(tokenizer.nextToken()))).longValue(); }else if (tokenNumber == morganColumn){ morganDistance = (new Long(new String(tokenizer.nextToken()))).longValue(); } else{ values.add(new String(tokenizer.nextToken())); } tokenNumber++; } if (tokenNumber != numColumns){ throw new PlinkException("Inconsistent column number on line " + (lineNumber+1)); } Marker assocMarker; if (!embed){ assocMarker = (Marker)markerHash.get(marker); if (assocMarker == null){ ignoredMarkers.add(marker); lineNumber++; continue; }else if (!(assocMarker.getChromosome().equalsIgnoreCase(chromosome)) && chromosome != null){ throw new PlinkException("Incompatible chromsomes."); } }else{ assocMarker = new Marker(chromosome,marker,morganDistance,position); } AssociationResult result = new AssociationResult(lineNumber,assocMarker,values); results.add(result); lineNumber++; } }catch(IOException ioe){ throw new PlinkException("File error."); }catch(NumberFormatException nfe){ throw new PlinkException("File formatting error."); } if (ignoredMarkers.size() != 0){ IgnoredMarkersDialog imd = new IgnoredMarkersDialog(hv,"Ignored Markers",ignoredMarkers,false); imd.pack(); imd.setVisible(true); } hv.setPlinkData(results,columns); } |
morganDistance = (new Long(new String(tokenizer.nextToken()))).longValue(); | morganDistance = (new Double(new String(tokenizer.nextToken()))).doubleValue(); | public void parseWGA(String wga, String map, boolean embed) throws PlinkException { markers = new Vector(); results = new Vector(); columns = new Vector(); columns.add("Result"); columns.add("Chrom"); columns.add("Marker"); columns.add("Position"); final File wgaFile = new File(wga); final File mapFile = new File(map); Hashtable markerHash = new Hashtable(1,1); Vector ignoredMarkers = new Vector(); try{ if (wgaFile.length() < 1){ throw new PlinkException("plink file is empty or nonexistent."); } if (!embed){ if (mapFile.length() < 1){ throw new PlinkException("Map file is empty or nonexistent."); } BufferedReader mapReader = new BufferedReader(new FileReader(mapFile)); String mapLine; String unknownChrom = "0"; while((mapLine = mapReader.readLine())!=null) { if (mapLine.length() == 0){ //skip blank lines continue; } StringTokenizer st = new StringTokenizer(mapLine,"\t "); String chrom = st.nextToken(); String chr; if (chrom.equals("0")){ chr = unknownChrom; }else if (chrom.equalsIgnoreCase("x") || chrom.equalsIgnoreCase("xy")){ chr = CHROM_NAMES[22]; } else{ chr = CHROM_NAMES[Integer.parseInt(chrom)-1]; } String marker = new String(st.nextToken()); long mDistance = Long.parseLong(st.nextToken()); long position = Long.parseLong(st.nextToken()); Marker mark = new Marker(chr, marker, mDistance, position); markers.add(mark); markerHash.put(mark.getMarkerID(), mark); } } BufferedReader wgaReader = new BufferedReader(new FileReader(wgaFile)); int numColumns = 0; int markerColumn = -1; int chromColumn = -1; int positionColumn = -1; int morganColumn = -1; String headerLine = wgaReader.readLine(); StringTokenizer headerSt = new StringTokenizer(headerLine); while (headerSt.hasMoreTokens()){ String column = new String(headerSt.nextToken()); if (column.equals("SNP")){ markerColumn = numColumns; numColumns++; }else if (column.equals("CHR")){ chromColumn = numColumns; numColumns++; }else if (column.equals("POS")){ positionColumn = numColumns; numColumns++; }else if (column.equals("MORGAN")){ morganColumn = numColumns; numColumns++; } else{ columns.add(column); numColumns++; } } if (markerColumn == -1){ throw new PlinkException("Results file must contain a SNP column."); } if (embed){ if (chromColumn == -1 || positionColumn == -1 || morganColumn == -1){ throw new PlinkException("Results files with embedded map files must contain CHR, POS, and MORGAN columns."); } } String wgaLine; int lineNumber = 0; while((wgaLine = wgaReader.readLine())!=null){ if (wgaLine.length() == 0){ //skip blank lines continue; } int tokenNumber = 0; //StringTokenizer tokenizer = new StringTokenizer(wgaLine,"\t :"); StringTokenizer tokenizer = new StringTokenizer(wgaLine); String marker = null; String chromosome = null; long position = 0; long morganDistance = 0; Vector values = new Vector(); while(tokenizer.hasMoreTokens()){ if (tokenNumber == markerColumn){ marker = new String(tokenizer.nextToken()); }else if (tokenNumber == chromColumn){ chromosome = new String(tokenizer.nextToken()); if(chromosome.equals("23")){ chromosome = "X"; } }else if (tokenNumber == positionColumn){ position = (new Long(new String(tokenizer.nextToken()))).longValue(); }else if (tokenNumber == morganColumn){ morganDistance = (new Long(new String(tokenizer.nextToken()))).longValue(); } else{ values.add(new String(tokenizer.nextToken())); } tokenNumber++; } if (tokenNumber != numColumns){ throw new PlinkException("Inconsistent column number on line " + (lineNumber+1)); } Marker assocMarker; if (!embed){ assocMarker = (Marker)markerHash.get(marker); if (assocMarker == null){ ignoredMarkers.add(marker); lineNumber++; continue; }else if (!(assocMarker.getChromosome().equalsIgnoreCase(chromosome)) && chromosome != null){ throw new PlinkException("Incompatible chromsomes."); } }else{ assocMarker = new Marker(chromosome,marker,morganDistance,position); } AssociationResult result = new AssociationResult(lineNumber,assocMarker,values); results.add(result); lineNumber++; } }catch(IOException ioe){ throw new PlinkException("File error."); }catch(NumberFormatException nfe){ throw new PlinkException("File formatting error."); } if (ignoredMarkers.size() != 0){ IgnoredMarkersDialog imd = new IgnoredMarkersDialog(hv,"Ignored Markers",ignoredMarkers,false); imd.pack(); imd.setVisible(true); } hv.setPlinkData(results,columns); } |
final DDLExportPanel ddlPanel = new DDLExportPanel(architectFrame.getProject()); Action okAction, cancelAction; okAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { try { if (ddlPanel.applyChanges()) { GenericDDLGenerator ddlg = architectFrame.getProject().getDDLGenerator(); ddlg.setTargetSchema(ddlPanel.getSchemaField().getText()); ddlg.generateDDL(architectFrame.getProject().getPlayPen().getDatabase()); List warnings = ddlg.getWarnings(); if (warnings.size() > 0) { TableSorter sorter = new TableSorter(new DDLWarningTableModel(warnings)); JTable warningTable = new JTable(sorter); sorter.setTableHeader(warningTable.getTableHeader()); JOptionPane.showMessageDialog(d, new JScrollPane(warningTable), "Warnings in generated DDL", JOptionPane.WARNING_MESSAGE); } SQLDatabase ppdb = ArchitectFrame.getMainInstance().getProject().getPlayPen().getDatabase(); SQLScriptDialog ssd = new SQLScriptDialog(d, "Preview SQL Script", "", false, ddlg, ppdb.getDataSource(), true); MonitorableWorker scriptWorker = ssd.getExecuteTask(); ConflictFinderProcess cfp = new ConflictFinderProcess(ssd, ppdb, ddlg, ddlg.getDdlStatements()); ConflictResolverProcess crp = new ConflictResolverProcess(ssd, cfp); cfp.setNextProcess(crp); crp.setNextProcess(scriptWorker); ssd.setExecuteTask(cfp); ssd.setVisible(true); } } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } } }; cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { ddlPanel.discardChanges(); d.setVisible(false); } }; d = ArchitectPanelBuilder.createArchitectPanelDialog( ddlPanel, ArchitectFrame.getMainInstance(), "Forward Engineer SQL Script", "OK", okAction, cancelAction); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } | final DDLExportPanel ddlPanel = new DDLExportPanel(architectFrame.getProject()); Action okAction, cancelAction; okAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { try { if (ddlPanel.applyChanges()) { GenericDDLGenerator ddlg = architectFrame.getProject().getDDLGenerator(); ddlg.setTargetSchema(ddlPanel.getSchemaField().getText()); for (;;) { ddlg.generateDDL(architectFrame.getProject().getPlayPen().getDatabase()); List warnings = ddlg.getWarnings(); if (warnings.size() == 0) break; TableSorter sorter = new TableSorter(new DDLWarningTableModel(warnings)); JTable warningTable = new JTable(sorter); sorter.setTableHeader(warningTable.getTableHeader()); int choice = JOptionPane.showConfirmDialog(d, new JScrollPane(warningTable), "Errors in generated DDL", JOptionPane.WARNING_MESSAGE); if (choice != JOptionPane.OK_OPTION) return; } SQLDatabase ppdb = ArchitectFrame.getMainInstance().getProject().getPlayPen().getDatabase(); SQLScriptDialog ssd = new SQLScriptDialog(d, "Preview SQL Script", "", false, ddlg, ppdb.getDataSource(), true); MonitorableWorker scriptWorker = ssd.getExecuteTask(); ConflictFinderProcess cfp = new ConflictFinderProcess(ssd, ppdb, ddlg, ddlg.getDdlStatements()); ConflictResolverProcess crp = new ConflictResolverProcess(ssd, cfp); cfp.setNextProcess(crp); crp.setNextProcess(scriptWorker); ssd.setExecuteTask(cfp); ssd.setVisible(true); } } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } } }; cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { ddlPanel.discardChanges(); d.setVisible(false); } }; d = ArchitectPanelBuilder.createArchitectPanelDialog( ddlPanel, ArchitectFrame.getMainInstance(), "Forward Engineer SQL Script", "OK", okAction, cancelAction); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } | public void actionPerformed(ActionEvent e) { final DDLExportPanel ddlPanel = new DDLExportPanel(architectFrame.getProject()); Action okAction, cancelAction; okAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { try { if (ddlPanel.applyChanges()) { GenericDDLGenerator ddlg = architectFrame.getProject().getDDLGenerator(); ddlg.setTargetSchema(ddlPanel.getSchemaField().getText()); // XXX is it OK that is this generated but never used?? ddlg.generateDDL(architectFrame.getProject().getPlayPen().getDatabase()); List warnings = ddlg.getWarnings(); if (warnings.size() > 0) { TableSorter sorter = new TableSorter(new DDLWarningTableModel(warnings)); JTable warningTable = new JTable(sorter); sorter.setTableHeader(warningTable.getTableHeader()); JOptionPane.showMessageDialog(d, new JScrollPane(warningTable), "Warnings in generated DDL", JOptionPane.WARNING_MESSAGE); } SQLDatabase ppdb = ArchitectFrame.getMainInstance().getProject().getPlayPen().getDatabase(); SQLScriptDialog ssd = new SQLScriptDialog(d, "Preview SQL Script", "", false, ddlg, ppdb.getDataSource(), true); MonitorableWorker scriptWorker = ssd.getExecuteTask(); ConflictFinderProcess cfp = new ConflictFinderProcess(ssd, ppdb, ddlg, ddlg.getDdlStatements()); ConflictResolverProcess crp = new ConflictResolverProcess(ssd, cfp); cfp.setNextProcess(crp); crp.setNextProcess(scriptWorker); ssd.setExecuteTask(cfp); ssd.setVisible(true); } } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } } }; cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { ddlPanel.discardChanges(); d.setVisible(false); } }; d = ArchitectPanelBuilder.createArchitectPanelDialog( ddlPanel, ArchitectFrame.getMainInstance(), "Forward Engineer SQL Script", "OK", okAction, cancelAction); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } |
try { if (ddlPanel.applyChanges()) { GenericDDLGenerator ddlg = architectFrame.getProject().getDDLGenerator(); ddlg.setTargetSchema(ddlPanel.getSchemaField().getText()); ddlg.generateDDL(architectFrame.getProject().getPlayPen().getDatabase()); List warnings = ddlg.getWarnings(); if (warnings.size() > 0) { TableSorter sorter = new TableSorter(new DDLWarningTableModel(warnings)); JTable warningTable = new JTable(sorter); sorter.setTableHeader(warningTable.getTableHeader()); JOptionPane.showMessageDialog(d, new JScrollPane(warningTable), "Warnings in generated DDL", JOptionPane.WARNING_MESSAGE); } SQLDatabase ppdb = ArchitectFrame.getMainInstance().getProject().getPlayPen().getDatabase(); SQLScriptDialog ssd = new SQLScriptDialog(d, "Preview SQL Script", "", false, ddlg, ppdb.getDataSource(), true); MonitorableWorker scriptWorker = ssd.getExecuteTask(); ConflictFinderProcess cfp = new ConflictFinderProcess(ssd, ppdb, ddlg, ddlg.getDdlStatements()); ConflictResolverProcess crp = new ConflictResolverProcess(ssd, cfp); cfp.setNextProcess(crp); crp.setNextProcess(scriptWorker); ssd.setExecuteTask(cfp); ssd.setVisible(true); } } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } } | try { if (ddlPanel.applyChanges()) { GenericDDLGenerator ddlg = architectFrame.getProject().getDDLGenerator(); ddlg.setTargetSchema(ddlPanel.getSchemaField().getText()); for (;;) { ddlg.generateDDL(architectFrame.getProject().getPlayPen().getDatabase()); List warnings = ddlg.getWarnings(); if (warnings.size() == 0) break; TableSorter sorter = new TableSorter(new DDLWarningTableModel(warnings)); JTable warningTable = new JTable(sorter); sorter.setTableHeader(warningTable.getTableHeader()); int choice = JOptionPane.showConfirmDialog(d, new JScrollPane(warningTable), "Errors in generated DDL", JOptionPane.WARNING_MESSAGE); if (choice != JOptionPane.OK_OPTION) return; } SQLDatabase ppdb = ArchitectFrame.getMainInstance().getProject().getPlayPen().getDatabase(); SQLScriptDialog ssd = new SQLScriptDialog(d, "Preview SQL Script", "", false, ddlg, ppdb.getDataSource(), true); MonitorableWorker scriptWorker = ssd.getExecuteTask(); ConflictFinderProcess cfp = new ConflictFinderProcess(ssd, ppdb, ddlg, ddlg.getDdlStatements()); ConflictResolverProcess crp = new ConflictResolverProcess(ssd, cfp); cfp.setNextProcess(crp); crp.setNextProcess(scriptWorker); ssd.setExecuteTask(cfp); ssd.setVisible(true); } } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } } | public void actionPerformed(ActionEvent evt) { try { if (ddlPanel.applyChanges()) { GenericDDLGenerator ddlg = architectFrame.getProject().getDDLGenerator(); ddlg.setTargetSchema(ddlPanel.getSchemaField().getText()); // XXX is it OK that is this generated but never used?? ddlg.generateDDL(architectFrame.getProject().getPlayPen().getDatabase()); List warnings = ddlg.getWarnings(); if (warnings.size() > 0) { TableSorter sorter = new TableSorter(new DDLWarningTableModel(warnings)); JTable warningTable = new JTable(sorter); sorter.setTableHeader(warningTable.getTableHeader()); JOptionPane.showMessageDialog(d, new JScrollPane(warningTable), "Warnings in generated DDL", JOptionPane.WARNING_MESSAGE); } SQLDatabase ppdb = ArchitectFrame.getMainInstance().getProject().getPlayPen().getDatabase(); SQLScriptDialog ssd = new SQLScriptDialog(d, "Preview SQL Script", "", false, ddlg, ppdb.getDataSource(), true); MonitorableWorker scriptWorker = ssd.getExecuteTask(); ConflictFinderProcess cfp = new ConflictFinderProcess(ssd, ppdb, ddlg, ddlg.getDdlStatements()); ConflictResolverProcess crp = new ConflictResolverProcess(ssd, cfp); cfp.setNextProcess(crp); crp.setNextProcess(scriptWorker); ssd.setExecuteTask(cfp); ssd.setVisible(true); } } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } } |
mi = new JMenuItem(af.deleteRelationshipAction); popup.add(mi); | protected void createPopup() { ArchitectFrame af = ArchitectFrame.getMainInstance(); popup = new JPopupMenu(); JMenuItem mi; mi = new JMenuItem(af.editRelationshipAction); popup.add(mi); addMouseListener(new PopupListener()); } |
|
if (e.getPropertyName() != null && e.getPropertyName().equals("name")) { setToolTipText(model.getName()); | if (e.getPropertyName() != null) { if (e.getPropertyName().equals("name")) { setToolTipText(model.getName()); } else if (e.getPropertyName().equals("identifying") || e.getPropertyName().equals("pkCardinality") || e.getPropertyName().equals("fkCardinality")) { repaint(); } | public void dbObjectChanged(SQLObjectEvent e) { if (e.getPropertyName() != null && e.getPropertyName().equals("name")) { setToolTipText(model.getName()); } } |
return tag.getProject(); | answer = tag.getProject(); | protected Project getProject() { ProjectTag tag = (ProjectTag) findAncestorWithClass(ProjectTag.class); if ( tag != null) { return tag.getProject(); } return (Project) context.findVariable( "org.apache.commons.jelly.werkz.Project" ); } |
return (Project) context.findVariable( "org.apache.commons.jelly.werkz.Project" ); | if (answer == null) { answer = (Project) context.findVariable( "org.apache.commons.jelly.werkz.Project" ); } return answer; | protected Project getProject() { ProjectTag tag = (ProjectTag) findAncestorWithClass(ProjectTag.class); if ( tag != null) { return tag.getProject(); } return (Project) context.findVariable( "org.apache.commons.jelly.werkz.Project" ); } |
if(((Integer)affStatus.elementAt(i)).intValue() != ((Integer)affStatus.elementAt(i+1)).intValue()) { | if(Options.getTdtType() == TDT_PAREN && ((Integer)affStatus.elementAt(i)) .intValue() != ((Integer)affStatus.elementAt(i+1)).intValue()) { | public void doAssociationTests(Vector affStatus, Vector permuteInd,Vector permuteDiscPar, Vector kidAffStatus) { if(fullProbMap == null || superdata == null || realAffectedStatus == null || realKidAffectedStatus == null) { return; } if(affStatus == null){ affStatus = realAffectedStatus; } if (kidAffStatus == null){ kidAffStatus = realKidAffectedStatus; } if(permuteInd == null) { permuteInd = new Vector(); for (int i = 0; i < superdata.length; i++){ permuteInd.add(new Boolean(false)); } } if(permuteDiscPar == null) { permuteDiscPar = new Vector(); for(int i=0; i< superdata.length; i++) { permuteDiscPar.add(new Boolean(false)); } } Vector caseCounts = new Vector(); Vector controlCounts = new Vector(); if (Options.getAssocTest() == ASSOC_CC){ MapWrap totalCase = new MapWrap(0); MapWrap totalControl = new MapWrap(0); for (int i = numFilteredTrios*2; i < superdata.length; i++){ MapWrap tempCase = new MapWrap(0); MapWrap tempControl = new MapWrap(0); double tempnorm=0; for (int n=0; n<superdata[i].nsuper; n++) { Long long1 = new Long(superdata[i].superposs[n].h1); Long long2 = new Long(superdata[i].superposs[n].h2); if (((Integer)affStatus.elementAt(i)).intValue() == 1){ tempControl.put(long1,tempControl.get(long1) + superdata[i].superposs[n].p); if(!haploid[i]){ tempControl.put(long2,tempControl.get(long2) + superdata[i].superposs[n].p); } }else if (((Integer)affStatus.elementAt(i)).intValue() == 2){ tempCase.put(long1,tempCase.get(long1) + superdata[i].superposs[n].p); if(!haploid[i]){ tempCase.put(long2,tempCase.get(long2) + superdata[i].superposs[n].p); } } tempnorm += superdata[i].superposs[n].p; } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempCase.get(curHap) > 0.0000 || tempControl.get(curHap) > 0.0000) { totalCase.put(curHap,totalCase.get(curHap) + (tempCase.get(curHap)/tempnorm)); totalControl.put(curHap,totalControl.get(curHap) + (tempControl.get(curHap)/tempnorm)); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { caseCounts.add(new Double(totalCase.get(sortedKeySet.get(j)))); controlCounts.add(new Double(totalControl.get(sortedKeySet.get(j)))); } } } Vector obsT = new Vector(); Vector obsU = new Vector(); if(Options.getAssocTest() == ASSOC_TRIO) { double product; MapWrap totalT = new MapWrap(0); MapWrap totalU = new MapWrap(0); discordantCounts = new Vector(); HashMap totalDiscordantCounts = new HashMap(); for (int i=0; i<numFilteredTrios*2; i+=2) { MapWrap tempT = new MapWrap(0); MapWrap tempU = new MapWrap(0); HashMap tempDiscordantCounts = new HashMap(); double tempnorm = 0; if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ boolean discordantParentPhenos = false; if(((Integer)affStatus.elementAt(i)).intValue() != ((Integer)affStatus.elementAt(i+1)).intValue()) { discordantParentPhenos = true; } for (int n=0; n<superdata[i].nsuper; n++) { for (int m=0; m<superdata[i+1].nsuper; m++) { if(kidConsistentCache[i/2][n][m]) { product=superdata[i].superposs[n].p*superdata[i+1].superposs[m].p; Long h1 = new Long(superdata[i].superposs[n].h1); Long h2 = new Long(superdata[i].superposs[n].h2); Long h3 = new Long(superdata[i+1].superposs[m].h1); Long h4 = new Long(superdata[i+1].superposs[m].h2); if(((Boolean)permuteInd.get(i)).booleanValue()) { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempU.put(h1, tempU.get(h1) + product); tempT.put(h2, tempT.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempU.put(h3, tempU.get(h3) + product); tempT.put(h4, tempT.get(h4) + product); } } else { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempT.put(h1, tempT.get(h1) + product); tempU.put(h2, tempU.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempT.put(h3, tempT.get(h3) + product); tempU.put(h4, tempU.get(h4) + product); } } // normalize by all possibilities, even double hom tempnorm+=product; if(discordantParentPhenos) { Long aff1,aff2,unaff1,unaff2; if(((Integer)affStatus.elementAt(i)).intValue() == 2) { aff1 = h1; aff2 = h2; unaff1 = h3; unaff2 = h4; }else { unaff1 = h1; unaff2 = h2; aff1 = h3; aff2 = h4; } //if were permuting then we switch the affected and unaffected if(((Boolean)permuteDiscPar.get(i)).booleanValue()){ Long temp1 = aff1; Long temp2 = aff2; aff1 = unaff1; aff2 = unaff2; unaff1 = temp1; unaff2 = temp2; } DiscordantTally dt = getTally(aff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); if(!aff2.equals(aff1)) { dt = getTally(aff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff1.equals(aff1) && !unaff1.equals(aff2)) { dt = getTally(unaff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff2.equals(aff1) && !unaff2.equals(aff2) && !unaff2.equals(unaff1)) { dt = getTally(unaff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } } } } } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempT.get(curHap) > 0.0000 || tempU.get(curHap) > 0.0000) { totalT.put(curHap, totalT.get(curHap) + tempT.get(curHap)/tempnorm); totalU.put(curHap, totalU.get(curHap) + tempU.get(curHap)/tempnorm); } } itr = tempDiscordantCounts.keySet().iterator(); while(itr.hasNext()) { Long key = (Long)itr.next(); DiscordantTally dt = (DiscordantTally) tempDiscordantCounts.get(key); dt.normalize(tempnorm); DiscordantTally totalDT = getTally(key,totalDiscordantCounts); totalDT.combine(dt); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { obsT.add(new Double(totalT.get(sortedKeySet.get(j)))); obsU.add(new Double(totalU.get(sortedKeySet.get(j)))); if(Options.getTdtType() == TDT_PAREN) { if(totalDiscordantCounts.containsKey(sortedKeySet.get(j))) { discordantCounts.add(((DiscordantTally)totalDiscordantCounts.get(sortedKeySet.get(j))).getCounts()); }else { discordantCounts.add(new double[9]); } } } } } if (Options.getAssocTest() == ASSOC_TRIO){ this.obsT = obsT; this.obsU = obsU; } else if (Options.getAssocTest() == ASSOC_CC){ this.caseCounts = caseCounts; this.controlCounts = controlCounts; } } |
guessBlocks(method, new Vector()); | guessBlocks(method, blocks); | void guessBlocks(int method){ guessBlocks(method, new Vector()); } |
cust.add(thisBlock); | if (thisBlock.length > 1){ cust.add(thisBlock); } | public Vector readBlocks(File infile) throws HaploViewException, IOException{ if (!infile.exists()){ throw new HaploViewException("File " + infile.getName() + " doesn't exist!"); } Vector cust = new Vector(); BufferedReader in = new BufferedReader(new FileReader(infile)); String currentLine; int lineCount = 0; int highestYet = -1; while ((currentLine = in.readLine()) != null){ lineCount ++; StringTokenizer st = new StringTokenizer(currentLine); if (st.countTokens() == 1){ //complain if we have only one col throw new HaploViewException("File error on line " + lineCount + " in " + infile.getName()); }else if (st.countTokens() == 0){ //skip blank lines continue; } try{ Vector goodies = new Vector(); while (st.hasMoreTokens()){ Integer nextInLine = new Integer(st.nextToken()); for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input file that are "good" from checkdata //we also realign the input file to the current "good" subset since input file is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == nextInLine.intValue() - 1){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int x = 0; x < goodies.size(); x++){ thisBlock[x] = ((Integer)goodies.elementAt(x)).intValue(); if (thisBlock[x] > Chromosome.getSize() || thisBlock[x] < 0){ throw new HaploViewException("Error, marker in block out of bounds: " + thisBlock[x] + "\non line " + lineCount); } if (thisBlock[x] <= highestYet){ throw new HaploViewException("Error, markers/blocks out of order or overlap:\n" + "on line " + lineCount); } highestYet = thisBlock[x]; } cust.add(thisBlock); }catch (NumberFormatException nfe) { throw new HaploViewException("Format error on line " + lineCount + " in " + infile.getName()); } } return cust; } |
protected void computeBounds() { | public void computeBounds() { | protected void computeBounds() { // XXX: should check for valid cached bounds before recomputing! TablePane pkTable = relationship.pkTable; TablePane fkTable = relationship.fkTable; if (!isOrientationLegal()) { // bestConnectionPoints also updates orientation as a side effect bestConnectionPoints(); } if (pkTable == fkTable) { // hack for supporting self-referencing table // assume orientation is PARENT_FACES_BOTTOM | CHILD_FACES_LEFT Point topLeft = new Point(fkConnectionPoint.x - getTerminationLength() * 2 - radius, fkConnectionPoint.y - getTerminationWidth()); Point bottomRight = new Point(pkConnectionPoint.x + getTerminationWidth(), pkConnectionPoint.y + radius + getTerminationLength() * 2); computedBounds = new Rectangle(topLeft.x + pkTable.getX(), topLeft.y + pkTable.getY(), bottomRight.x - topLeft.x, bottomRight.y - topLeft.y); } else { Point pkLimits = new Point(pkConnectionPoint); pkLimits.translate(pkTable.getX(), pkTable.getY()); Point fkLimits = new Point(fkConnectionPoint); fkLimits.translate(fkTable.getX(), fkTable.getY()); if (logger.isDebugEnabled()) { logger.debug("Absolute connection points: pk="+pkLimits+"; fk="+fkLimits); } // make room for parent decorations if ( (orientation & (PARENT_FACES_RIGHT | PARENT_FACES_LEFT)) != 0) { if (pkLimits.y >= fkLimits.y) { pkLimits.y += getTerminationWidth(); } else { pkLimits.y -= getTerminationWidth(); } } else { if (pkLimits.x >= fkLimits.x) { pkLimits.x += getTerminationWidth(); } else { pkLimits.x -= getTerminationWidth(); } } // make room for child decorations if ( (orientation & (CHILD_FACES_RIGHT | CHILD_FACES_LEFT)) != 0) { if (fkLimits.y <= pkConnectionPoint.y + pkTable.getY()) { fkLimits.y -= getTerminationWidth(); } else { fkLimits.y += getTerminationWidth(); } } else { if (fkLimits.x <= pkConnectionPoint.x + pkTable.getX()) { fkLimits.x -= getTerminationWidth(); } else { fkLimits.x += getTerminationWidth(); } } if (logger.isDebugEnabled()) logger.debug("Limits: pk="+pkLimits+"; fk="+fkLimits); Point topLeft = new Point(Math.min(pkLimits.x, fkLimits.x), Math.min(pkLimits.y, fkLimits.y)); Point bottomRight = new Point(Math.max(pkLimits.x, fkLimits.x), Math.max(pkLimits.y, fkLimits.y)); computedBounds = new Rectangle(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y); if (logger.isDebugEnabled()) { logger.debug("Updating bounds to "+computedBounds +" (topleft="+topLeft+"; bottomRight="+bottomRight+")"); } } relationship.setBounds(computedBounds.x, computedBounds.y, computedBounds.width, computedBounds.height); } |
((ProfileTableModel)viewTable.getModel()).refresh(); | TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); | public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); d.setVisible(false); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, new CommonCloseAction(d)); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(tm); final JTable viewTable = new ProfileTable(tableModelSortDecorator); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths tableModelSortDecorator.initColumnSizes(viewTable); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); int response = chooser.showSaveDialog(d); if (response != JFileChooser.APPROVE_OPTION) { return; } else { File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!file.getPath().endsWith(".html")) { file = new File(file.getPath()+".html"); } } else { if (!file.getPath().endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( d, "The file\n\n"+file.getPath()+"\n\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { List tabList = new ArrayList(tables); OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file2)); if (fileFilter == ASUtils.HTML_FILE_FILTER){ final String encoding = "utf-8"; ProfileHTMLFormat prf = new ProfileHTMLFormat(encoding); OutputStreamWriter osw = new OutputStreamWriter(out, encoding); osw.append(prf.format(tabList,profileManager)); osw.flush(); } else { new ProfilePDFFormat().createPdf(out, tabList, profileManager); } } catch (Exception ex) { ASUtils.showExceptionDialog(d,"Could not save PDF File", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(d,"Could not close PDF File", ex); } } } } }; new Thread(saveTask).start(); } } }); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } ((ProfileTableModel)viewTable.getModel()).refresh(); } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete column:", e1); } } // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { profileManager.clear(); // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } } |
((ProfileTableModel)viewTable.getModel()).refresh(); | TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); | public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(tm); final JTable viewTable = new ProfileTable(tableModelSortDecorator); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths tableModelSortDecorator.initColumnSizes(viewTable); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); int response = chooser.showSaveDialog(d); if (response != JFileChooser.APPROVE_OPTION) { return; } else { File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!file.getPath().endsWith(".html")) { file = new File(file.getPath()+".html"); } } else { if (!file.getPath().endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( d, "The file\n\n"+file.getPath()+"\n\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { List tabList = new ArrayList(tables); OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file2)); if (fileFilter == ASUtils.HTML_FILE_FILTER){ final String encoding = "utf-8"; ProfileHTMLFormat prf = new ProfileHTMLFormat(encoding); OutputStreamWriter osw = new OutputStreamWriter(out, encoding); osw.append(prf.format(tabList,profileManager)); osw.flush(); } else { new ProfilePDFFormat().createPdf(out, tabList, profileManager); } } catch (Exception ex) { ASUtils.showExceptionDialog(d,"Could not save PDF File", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(d,"Could not close PDF File", ex); } } } } }; new Thread(saveTask).start(); } } }); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } ((ProfileTableModel)viewTable.getModel()).refresh(); } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete column:", e1); } } // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { profileManager.clear(); // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } |
((ProfileTableModel)viewTable.getModel()).refresh(); | TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); | public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } ((ProfileTableModel)viewTable.getModel()).refresh(); } |
model.removeColumn(idx); | public ColumnEditPanel(SQLTable table, int idx) throws ArchitectException { super(new BorderLayout(12,12)); JPanel westPanel = new JPanel(new BorderLayout()); columns = new JList(); columns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); columns.addListSelectionListener(this); westPanel.add(new JScrollPane(columns), BorderLayout.CENTER); setModel(table); JPanel addDelPanel = new JPanel(new FlowLayout()); addDelPanel.add(addColumnButton = new JButton("Add")); addColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { try { idx = model.getColumns().size(); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); idx = 0; } } else { idx++; // add after selected column } SQLColumn col = new SQLColumn(); col.setColumnName("new column"); model.addColumn(idx, col); columns.setSelectedIndex(idx); } }); addDelPanel.add(deleteColumnButton = new JButton("Del")); deleteColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } }); westPanel.add(addDelPanel, BorderLayout.SOUTH); add(westPanel, BorderLayout.WEST); JPanel centerBox = new JPanel(); centerBox.setLayout(new BoxLayout(centerBox, BoxLayout.Y_AXIS)); centerBox.add(Box.createVerticalGlue()); JPanel centerPanel = new JPanel(); centerPanel.setLayout(new FormLayout(5, 5)); centerPanel.setBorder(BorderFactory.createTitledBorder("Column Properties")); centerPanel.add(new JLabel("Source Database")); centerPanel.add(sourceDB = new JLabel()); centerPanel.add(new JLabel("Source Table.Column")); centerPanel.add(sourceTableCol = new JLabel()); centerPanel.add(new JLabel("Name")); centerPanel.add(colName = new JTextField()); colName.addActionListener(this); colName.getDocument().addDocumentListener(this); centerPanel.add(new JLabel("Type")); centerPanel.add(colType = createColTypeEditor()); colType.addActionListener(this); centerPanel.add(new JLabel("Scale")); centerPanel.add(colScale = createScaleEditor()); colScale.addChangeListener(this); centerPanel.add(new JLabel("Precision")); centerPanel.add(colPrec = createPrecisionEditor()); colPrec.addChangeListener(this); centerPanel.add(new JLabel("In Primary Key")); centerPanel.add(colInPK = new JCheckBox()); colInPK.addActionListener(this); centerPanel.add(new JLabel("Allows Nulls")); centerPanel.add(colNullable = new JCheckBox()); colNullable.addActionListener(this); centerPanel.add(new JLabel("Auto Increment")); centerPanel.add(colAutoInc = new JCheckBox()); colAutoInc.addActionListener(this); centerPanel.add(new JLabel("Remarks")); centerPanel.add(colRemarks = new JTextField()); colRemarks.addActionListener(this); centerPanel.add(new JLabel("Default Value")); centerPanel.add(colDefaultValue = new JTextField()); colDefaultValue.addActionListener(this); Dimension maxSize = centerPanel.getLayout().preferredLayoutSize(centerPanel); maxSize.width = Integer.MAX_VALUE; centerPanel.setMaximumSize(maxSize); centerBox.add(centerPanel); centerBox.add(Box.createVerticalGlue()); add(centerBox, BorderLayout.CENTER); // select the default column columns.setSelectedIndex(idx); } |
|
if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); | if (idx == size - 1) { columns.setSelectedIndex(size-2); model.removeColumn(idx); } else { model.removeColumn(idx); columns.setSelectedIndex(idx); | public ColumnEditPanel(SQLTable table, int idx) throws ArchitectException { super(new BorderLayout(12,12)); JPanel westPanel = new JPanel(new BorderLayout()); columns = new JList(); columns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); columns.addListSelectionListener(this); westPanel.add(new JScrollPane(columns), BorderLayout.CENTER); setModel(table); JPanel addDelPanel = new JPanel(new FlowLayout()); addDelPanel.add(addColumnButton = new JButton("Add")); addColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { try { idx = model.getColumns().size(); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); idx = 0; } } else { idx++; // add after selected column } SQLColumn col = new SQLColumn(); col.setColumnName("new column"); model.addColumn(idx, col); columns.setSelectedIndex(idx); } }); addDelPanel.add(deleteColumnButton = new JButton("Del")); deleteColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } }); westPanel.add(addDelPanel, BorderLayout.SOUTH); add(westPanel, BorderLayout.WEST); JPanel centerBox = new JPanel(); centerBox.setLayout(new BoxLayout(centerBox, BoxLayout.Y_AXIS)); centerBox.add(Box.createVerticalGlue()); JPanel centerPanel = new JPanel(); centerPanel.setLayout(new FormLayout(5, 5)); centerPanel.setBorder(BorderFactory.createTitledBorder("Column Properties")); centerPanel.add(new JLabel("Source Database")); centerPanel.add(sourceDB = new JLabel()); centerPanel.add(new JLabel("Source Table.Column")); centerPanel.add(sourceTableCol = new JLabel()); centerPanel.add(new JLabel("Name")); centerPanel.add(colName = new JTextField()); colName.addActionListener(this); colName.getDocument().addDocumentListener(this); centerPanel.add(new JLabel("Type")); centerPanel.add(colType = createColTypeEditor()); colType.addActionListener(this); centerPanel.add(new JLabel("Scale")); centerPanel.add(colScale = createScaleEditor()); colScale.addChangeListener(this); centerPanel.add(new JLabel("Precision")); centerPanel.add(colPrec = createPrecisionEditor()); colPrec.addChangeListener(this); centerPanel.add(new JLabel("In Primary Key")); centerPanel.add(colInPK = new JCheckBox()); colInPK.addActionListener(this); centerPanel.add(new JLabel("Allows Nulls")); centerPanel.add(colNullable = new JCheckBox()); colNullable.addActionListener(this); centerPanel.add(new JLabel("Auto Increment")); centerPanel.add(colAutoInc = new JCheckBox()); colAutoInc.addActionListener(this); centerPanel.add(new JLabel("Remarks")); centerPanel.add(colRemarks = new JTextField()); colRemarks.addActionListener(this); centerPanel.add(new JLabel("Default Value")); centerPanel.add(colDefaultValue = new JTextField()); colDefaultValue.addActionListener(this); Dimension maxSize = centerPanel.getLayout().preferredLayoutSize(centerPanel); maxSize.width = Integer.MAX_VALUE; centerPanel.setMaximumSize(maxSize); centerBox.add(centerPanel); centerBox.add(Box.createVerticalGlue()); add(centerBox, BorderLayout.CENTER); // select the default column columns.setSelectedIndex(idx); } |
model.removeColumn(idx); | public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } |
|
if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); | if (idx == size - 1) { columns.setSelectedIndex(size-2); model.removeColumn(idx); } else { model.removeColumn(idx); columns.setSelectedIndex(idx); | public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } |
public void runScript(String uri, XMLOutput output) throws Exception { URL url = getResource(uri); if (url == null) { throw new JellyException("Could not find Jelly script: " + url); } Script script = compileScript(url); URL newJellyContextURL = getJellyContextURL(url); JellyContext newJellyContext = new JellyContext(this, newJellyContextURL); script.run(newJellyContext, output); | public void runScript(File file, XMLOutput output) throws Exception { runScript(file.toURL(), output); | public void runScript(String uri, XMLOutput output) throws Exception { URL url = getResource(uri); if (url == null) { throw new JellyException("Could not find Jelly script: " + url); } Script script = compileScript(url); URL newJellyContextURL = getJellyContextURL(url); JellyContext newJellyContext = new JellyContext(this, newJellyContextURL); script.run(newJellyContext, output); } |
db.setIgnoreReset(true); | db.setPlayPenDatabase(true); | private final void setDatabase(SQLDatabase newdb) { if (newdb == null) throw new NullPointerException("db must be non-null"); this.db = newdb; db.setIgnoreReset(true); if (db.getDataSource() == null) { ArchitectDataSource dbcs = new ArchitectDataSource(); dbcs.setName("Not Configured"); dbcs.setDisplayName("Not Configured"); db.setDataSource(dbcs); } try { ArchitectUtils.listenToHierarchy(this, db); } catch (ArchitectException ex) { logger.error("Couldn't listen to database", ex); } tableNames = new HashSet(); } |
ResultSet mdTables = null; | ResultSet rs = null; | protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } } |
mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { | rs = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (rs.next()) { | protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } } |
String catName = mdTables.getString(1); | String catName = rs.getString(1); | protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } } |
String schName = mdTables.getString(2); | String schName = rs.getString(2); | protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } } |
mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), | rs.getString(3), rs.getString(5), rs.getString(4), | protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } } |
if (mdTables != null) mdTables.close(); | if (rs != null) rs.close(); | protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } } |
logger.error("Selection list and children are out of sync: selection="+columnSelection+"; children="+model.getChildren()); | logger.error("Selection list and children are out of sync: selection="+columnSelection+"; children="+this.model.getColumns()); | public void dbChildrenRemoved(SQLObjectEvent e) { if (e.getSource() == this.model.getColumnsFolder()) { int ci[] = e.getChangedIndices(); for (int i = 0; i < ci.length; i++) { columnSelection.remove(ci[i]); } if (columnSelection.size() > 0) { selectNone(); columnSelection.set(Math.min(ci[0], columnSelection.size()-1), Boolean.TRUE); } } try { ArchitectUtils.unlistenToHierarchy(this, e.getChildren()); if (columnSelection.size() != this.model.getColumns().size()) { logger.error("Selection list and children are out of sync: selection="+columnSelection+"; children="+model.getChildren()); } } catch (ArchitectException ex) { logger.error("Couldn't remove children", ex); JOptionPane.showMessageDialog(this, "Couldn't delete column: "+ex.getMessage()); } firePropertyChange("model.children", null, null); revalidate(); } |
catch (Error e) { handleException(e); } | public void run(JellyContext context, XMLOutput output) throws Exception { if ( ! context.isCacheTags() ) { clearTag(); } try { Tag tag = getTag(); if ( tag == null ) { return; } tag.setContext(context); if ( tag instanceof DynaTag ) { DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Class type = dynaTag.getAttributeType(name); Object value = null; if (type != null && type.isAssignableFrom(Expression.class) && !type.isAssignableFrom(Object.class)) { value = expression; } else { value = expression.evaluate(context); } dynaTag.setAttribute(name, value); } } else { // treat the tag as a bean DynaBean dynaBean = new ConvertingWrapDynaBean( tag ); for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); DynaProperty property = dynaBean.getDynaClass().getDynaProperty(name); if (property == null) { throw new JellyException("This tag does not understand the '" + name + "' attribute" ); } Class type = property.getType(); Object value = null; if (type.isAssignableFrom(Expression.class) && !type.isAssignableFrom(Object.class)) { value = expression; } else { value = expression.evaluate(context); } dynaBean.set(name, value); } } tag.doTag(output); } catch (JellyException e) { handleException(e); } catch (Exception e) { handleException(e); } } |
|
log.info("Deleting bogus entry: " + replicaEntry); | log.info("Deleting bogus replica entry: " + replicaEntry); | void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } } |
replicaEntry.tryDelete(); | try { replicaEntry.tryDelete(); } catch (PersistException e) { log.error("Unable to delete replica entry: " + replicaEntry, e); if (masterEntry != null) { S newReplicaEntry = mReplicaStorage.prepare(); transferToReplicaEntry(replicaEntry, masterEntry, newReplicaEntry); log.info("Replacing corrupt replica entry with: " + newReplicaEntry); try { newReplicaEntry.update(); } catch (PersistException e2) { log.error("Unable to update replica entry: " + replicaEntry, e2); return; } } } | void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.