rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
Connection con = null; SQLDatabase target = architectFrame.playpen.getDatabase(); try { con = target.getConnection(); statements = ddlg.generateDDLStatements(target); Set conflicts = new TreeSet(); Iterator it = statements.iterator(); while (it.hasNext()) { DDLStatement stmt = (DDLStatement) it.next(); conflicts.addAll(DDLUtils.findConflicting(con, stmt)); } if (!conflicts.isEmpty()) { String msg = "The following objects which you are trying" +"\nto create in the target database already exist:" +"\n\n" +conflicts +"\n\n" +"Do you want the Architect to drop these objects before" +"attempting to create the new ones?"; int choice = JOptionPane.showConfirmDialog(dialog, msg, "Conflicting Objects Found", JOptionPane.YES_NO_CANCEL_OPTION); if (choice == JOptionPane.YES_OPTION) { DDLUtils.dropConflicting(con, conflicts); } else if (choice == JOptionPane.CANCEL_OPTION) { cancelled = true; } } } catch (ArchitectException ex) { JOptionPane.showMessageDialog (dialog, "Couldn't connect to target database: "+ex.getMessage() +"\nPlease check the connection settings and try again."); ArchitectFrame.getMainInstance().playpen.showDbcsDialog(); finished = true; return; } catch (Exception ex) { logger.error("Unexpected exception setting up DDL generation", ex); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog (dialog, "You have to specify a target database connection" +"\nbefore executing this script."); ArchitectFrame.getMainInstance().playpen.showDbcsDialog(); } }); finished = true; return; } | public void prepareToStart() { finished = false; cancelled = false; } |
|
(dialog, "Couldn't connect to target database: "+fex.getMessage() +"\nPlease check the connection settings and try again."); | (dialog, "You have to specify a target database connection" +"\nbefore executing this script."); | public void run() { JOptionPane.showMessageDialog (dialog, "Couldn't connect to target database: "+fex.getMessage() +"\nPlease check the connection settings and try again."); ArchitectFrame.getMainInstance().playpen.showDbcsDialog(); } |
logger.debug("Finding conflicts for TABLE '"+t.getCatalogName()+"'.'"+t.getSchemaName()+"'.'"+t.getName()+"'"); | logger.debug("Finding conflicts for TABLE '"+cat+"'.'"+sch+"'.'"+t.getName()+"'"); | public static List findConflicting(Connection con, DDLStatement ddlStmt) throws SQLException { List conflicts = new ArrayList(); SQLObject so = ddlStmt.getObject(); Class clazz = so.getClass(); if (clazz.equals(SQLTable.class)) { SQLTable t = (SQLTable) so; DatabaseMetaData dbmd = con.getMetaData(); if (logger.isDebugEnabled()) { logger.debug("Finding conflicts for TABLE '"+t.getCatalogName()+"'.'"+t.getSchemaName()+"'.'"+t.getName()+"'"); } ResultSet rs = dbmd.getTables(t.getCatalogName(), t.getSchemaName(), t.getName(), null); while (rs.next()) { StringBuffer qualName = new StringBuffer(); if (rs.getString("TABLE_CAT") != null) { qualName.append(rs.getString("TABLE_CAT")); } if (rs.getString("TABLE_SCHEM") != null) { if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_SCHEM")); } if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_NAME")); qualName.insert(0, rs.getString("TABLE_TYPE")); conflicts.add(qualName); } } else if (clazz.equals(SQLRelationship.class)) { logger.error("Relationship conflicts are not supported yet!"); } else { throw new IllegalArgumentException("Unknown subclass of SQLObject: "+clazz.getName()); } return conflicts; } |
ResultSet rs = dbmd.getTables(t.getCatalogName(), t.getSchemaName(), t.getName(), null); | ResultSet rs = dbmd.getTables(cat, sch, t.getName(), null); | public static List findConflicting(Connection con, DDLStatement ddlStmt) throws SQLException { List conflicts = new ArrayList(); SQLObject so = ddlStmt.getObject(); Class clazz = so.getClass(); if (clazz.equals(SQLTable.class)) { SQLTable t = (SQLTable) so; DatabaseMetaData dbmd = con.getMetaData(); if (logger.isDebugEnabled()) { logger.debug("Finding conflicts for TABLE '"+t.getCatalogName()+"'.'"+t.getSchemaName()+"'.'"+t.getName()+"'"); } ResultSet rs = dbmd.getTables(t.getCatalogName(), t.getSchemaName(), t.getName(), null); while (rs.next()) { StringBuffer qualName = new StringBuffer(); if (rs.getString("TABLE_CAT") != null) { qualName.append(rs.getString("TABLE_CAT")); } if (rs.getString("TABLE_SCHEM") != null) { if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_SCHEM")); } if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_NAME")); qualName.insert(0, rs.getString("TABLE_TYPE")); conflicts.add(qualName); } } else if (clazz.equals(SQLRelationship.class)) { logger.error("Relationship conflicts are not supported yet!"); } else { throw new IllegalArgumentException("Unknown subclass of SQLObject: "+clazz.getName()); } return conflicts; } |
qualName.insert(0, rs.getString("TABLE_TYPE")); conflicts.add(qualName); | qualName.insert(0, rs.getString("TABLE_TYPE")+" "); conflicts.add(qualName.toString()); | public static List findConflicting(Connection con, DDLStatement ddlStmt) throws SQLException { List conflicts = new ArrayList(); SQLObject so = ddlStmt.getObject(); Class clazz = so.getClass(); if (clazz.equals(SQLTable.class)) { SQLTable t = (SQLTable) so; DatabaseMetaData dbmd = con.getMetaData(); if (logger.isDebugEnabled()) { logger.debug("Finding conflicts for TABLE '"+t.getCatalogName()+"'.'"+t.getSchemaName()+"'.'"+t.getName()+"'"); } ResultSet rs = dbmd.getTables(t.getCatalogName(), t.getSchemaName(), t.getName(), null); while (rs.next()) { StringBuffer qualName = new StringBuffer(); if (rs.getString("TABLE_CAT") != null) { qualName.append(rs.getString("TABLE_CAT")); } if (rs.getString("TABLE_SCHEM") != null) { if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_SCHEM")); } if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_NAME")); qualName.insert(0, rs.getString("TABLE_TYPE")); conflicts.add(qualName); } } else if (clazz.equals(SQLRelationship.class)) { logger.error("Relationship conflicts are not supported yet!"); } else { throw new IllegalArgumentException("Unknown subclass of SQLObject: "+clazz.getName()); } return conflicts; } |
if (logger.isDebugEnabled()) logger.debug("Found conflicts: "+conflicts); | public static List findConflicting(Connection con, DDLStatement ddlStmt) throws SQLException { List conflicts = new ArrayList(); SQLObject so = ddlStmt.getObject(); Class clazz = so.getClass(); if (clazz.equals(SQLTable.class)) { SQLTable t = (SQLTable) so; DatabaseMetaData dbmd = con.getMetaData(); if (logger.isDebugEnabled()) { logger.debug("Finding conflicts for TABLE '"+t.getCatalogName()+"'.'"+t.getSchemaName()+"'.'"+t.getName()+"'"); } ResultSet rs = dbmd.getTables(t.getCatalogName(), t.getSchemaName(), t.getName(), null); while (rs.next()) { StringBuffer qualName = new StringBuffer(); if (rs.getString("TABLE_CAT") != null) { qualName.append(rs.getString("TABLE_CAT")); } if (rs.getString("TABLE_SCHEM") != null) { if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_SCHEM")); } if (qualName.length() > 0) qualName.append("."); qualName.append(rs.getString("TABLE_NAME")); qualName.insert(0, rs.getString("TABLE_TYPE")); conflicts.add(qualName); } } else if (clazz.equals(SQLRelationship.class)) { logger.error("Relationship conflicts are not supported yet!"); } else { throw new IllegalArgumentException("Unknown subclass of SQLObject: "+clazz.getName()); } return conflicts; } |
|
public static void dropConflicting(Connection con, List objectNames) throws SQLException { | public static void dropConflicting(Connection con, Collection objectNames) throws SQLException { | public static void dropConflicting(Connection con, List objectNames) throws SQLException { Iterator it = objectNames.iterator(); Statement stmt = null; try { while (it.hasNext()) { String objectName = (String) it.next(); stmt = con.createStatement(); stmt.executeUpdate("DROP "+objectName); } } finally { if (stmt != null) stmt.close(); } } |
propertiesToIgnore.add("zoomInAction"); propertiesToIgnore.add("zoomOutAction"); | public void testAllSettersAreUndoable() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ArchitectException { SQLObject so = getSQLObjectUnderTest(); Set<String>propertiesToIgnore = new HashSet<String>(); propertiesToIgnore.add("populated"); propertiesToIgnore.add("SQLObjectListeners"); propertiesToIgnore.add("children"); propertiesToIgnore.add("parent"); propertiesToIgnore.add("parentDatabase"); propertiesToIgnore.add("class"); propertiesToIgnore.add("childCount"); propertiesToIgnore.add("undoEventListeners"); propertiesToIgnore.add("connection"); propertiesToIgnore.add("typeMap"); propertiesToIgnore.add("secondaryChangeMode"); if(so instanceof SQLDatabase) { // should be handled in the Datasource propertiesToIgnore.add("name"); } UndoManager undoManager= new UndoManager(so); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass())); if(so instanceof SQLDatabase) { // should be handled in the Datasource settableProperties.remove("name"); } for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnore.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(so, property.getName()); if (property.getWriteMethod() == null) { continue; } } catch (NoSuchMethodException e) { System.out.println("Skipping non-settable property "+property.getName()+" on "+so.getClass().getName()); continue; } Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value if (property.getPropertyType() == Integer.TYPE ) { newVal = ((Integer)oldVal)+1; } else if (property.getPropertyType() == String.class) { // make sure it's unique newVal ="new " + oldVal; } else if (property.getPropertyType() == Boolean.TYPE){ newVal = new Boolean(! ((Boolean) oldVal).booleanValue()); } else if (property.getPropertyType() == SQLCatalog.class) { newVal = new SQLCatalog(new SQLDatabase(),"This is a new catalog"); } else if (property.getPropertyType() == ArchitectDataSource.class) { newVal = new ArchitectDataSource(); ((ArchitectDataSource)newVal).setName("test"); ((ArchitectDataSource)newVal).setDisplayName("test"); ((ArchitectDataSource)newVal).setUser("a"); ((ArchitectDataSource)newVal).setPass("b"); ((ArchitectDataSource)newVal).setDriverClass(MockJDBCDriver.class.getName()); ((ArchitectDataSource)newVal).setUrl("jdbc:mock:x=y"); } else if (property.getPropertyType() == SQLTable.class) { newVal = new SQLTable(); } else { throw new RuntimeException("This test case lacks a value for "+ property.getName()+ " (type "+property.getPropertyType().getName()+") from "+so.getClass()); } int oldChangeCount = undoManager.getUndoableEditCount(); try { BeanUtils.copyProperty(so, property.getName(), newVal); // some setters fire multiple events (they change more than one property) but only register one as an undo assertEquals("Event for set "+property.getName()+" on "+so.getClass().getName()+" added multiple undos!", oldChangeCount+1,undoManager.getUndoableEditCount()); } catch (InvocationTargetException e) { System.out.println("(non-fatal) Failed to write property '"+property.getName()+" to type "+so.getClass().getName()); } } } |
|
propertiesToIgnore.add("secondaryChangeMode"); | propertiesToIgnore.add("secondaryChangeMode"); propertiesToIgnore.add("zoomInAction"); propertiesToIgnore.add("zoomOutAction"); | public void testAllSettersGenerateEvents() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { SQLObject so = getSQLObjectUnderTest(); Set<String>propertiesToIgnore = new HashSet<String>(); propertiesToIgnore.add("populated"); propertiesToIgnore.add("SQLObjectListeners"); propertiesToIgnore.add("children"); propertiesToIgnore.add("parent"); propertiesToIgnore.add("parentDatabase"); propertiesToIgnore.add("class"); propertiesToIgnore.add("childCount"); propertiesToIgnore.add("undoEventListeners"); propertiesToIgnore.add("connection"); propertiesToIgnore.add("typeMap"); propertiesToIgnore.add("secondaryChangeMode"); if(so instanceof SQLDatabase) { // should be handled in the Datasource propertiesToIgnore.add("name"); } CountingSQLObjectListener listener = new CountingSQLObjectListener(); so.addSQLObjectListener(listener); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass())); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnore.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(so, property.getName()); // check for a setter if (property.getWriteMethod() == null) { continue; } } catch (NoSuchMethodException e) { System.out.println("Skipping non-settable property "+property.getName()+" on "+so.getClass().getName()); continue; } Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value if (property.getPropertyType() == Integer.TYPE ) { newVal = ((Integer)oldVal)+1; } else if (property.getPropertyType() == String.class) { // make sure it's unique newVal ="new " + oldVal; } else if (property.getPropertyType() == Boolean.TYPE){ newVal = new Boolean(! ((Boolean) oldVal).booleanValue()); } else if (property.getPropertyType() == SQLCatalog.class) { newVal = new SQLCatalog(new SQLDatabase(),"This is a new catalog"); } else if (property.getPropertyType() == ArchitectDataSource.class) { newVal = new ArchitectDataSource(); ((ArchitectDataSource)newVal).setName("test"); ((ArchitectDataSource)newVal).setDisplayName("test"); ((ArchitectDataSource)newVal).setUser("a"); ((ArchitectDataSource)newVal).setPass("b"); ((ArchitectDataSource)newVal).setDriverClass(MockJDBCDriver.class.getName()); ((ArchitectDataSource)newVal).setUrl("jdbc:mock:x=y"); } else if (property.getPropertyType() == SQLTable.class) { newVal = new SQLTable(); } else { throw new RuntimeException("This test case lacks a value for "+ property.getName()+ " (type "+property.getPropertyType().getName()+") from "+so.getClass()); } int oldChangeCount = listener.getChangedCount(); try { BeanUtils.copyProperty(so, property.getName(), newVal); // some setters fire multiple events (they change more than one property) assertTrue("Event for set "+property.getName()+" on "+so.getClass().getName()+" didn't fire!", listener.getChangedCount() > oldChangeCount); if (listener.getChangedCount() == oldChangeCount + 1) { assertEquals("Property name mismatch for "+property.getName()+ " in "+so.getClass(), property.getName(), listener.getLastEvent().getPropertyName()); assertEquals("New value for "+property.getName()+" was wrong", newVal, listener.getLastEvent().getNewValue()); } } catch (InvocationTargetException e) { System.out.println("(non-fatal) Failed to write property '"+property.getName()+" to type "+so.getClass().getName()); } } } |
thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); | protected void createThumbnail( Volume volume ) { // Find the original image to use as a staring point ImageInstance original = null; if ( instances == null ) { getInstances(); } for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; break; } } if ( original == null ) { System.err.println( "Error - no original image was found!!!" ); } // Read the image BufferedImage origImage = null; try { origImage = ImageIO.read( original.getImageFile() ); } catch ( IOException e ) { System.err.println( "Error reading image: " + e.getMessage() ); return; } // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); int maxThumbWidth = 100; int maxThumbHeight = 100; float widthScale = (float) maxThumbWidth / (float) origWidth; float heightScale = (float) maxThumbHeight / (float) origHeight; float scale = widthScale; if ( heightScale < widthScale ) { scale = heightScale; } System.err.println( "Scaling to thumbnail from (" + origWidth + ", " + origHeight + " by " + scale ); // Thhen create the xform AffineTransform at = new AffineTransform(); at.scale( scale, scale ); AffineTransformOp scaleOp = new AffineTransformOp( at, AffineTransformOp.TYPE_BILINEAR ); // Create the target image int thumbWidth = (int)(((float)origWidth) * scale); int thumbHeight = (int)(((float)origHeight) * scale); System.err.println( "Thumbnail size (" + thumbWidth + ", " + thumbHeight + ")" ); BufferedImage thumbImage = new BufferedImage( thumbWidth, thumbHeight, origImage.getType() ); scaleOp.filter( origImage, thumbImage ); // Save it try { ImageIO.write( thumbImage, "jpg", thumbnailFile ); } catch ( IOException e ) { System.err.println( "Error writing thumbnail: " + e.getMessage() ); } // add the created instance to this perdsisten object addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); } |
|
if (command == "Open Haplotype File" || command == "Open Linkage File"){ | String shortHapInputFileName; if (command == "Open Linkage File"){ | public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Open Haplotype File" || command == "Open Linkage File"){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File inputFile = fc.getSelectedFile(); if (command == "Open Linkage File"){ //pop open checkdata window JFrame checkWindow = new JFrame(); CheckDataPanel checkPanel = new CheckDataPanel(inputFile); checkWindow.setTitle("Checking markers..."); checkWindow.add(checkPanel); checkWindow.add(new JButton("FOO")); checkWindow.pack(); checkWindow.setVisible(true); } try{ theData = new HaploData(inputFile); infileName = inputFile.getName(); //compute D primes and monitor progress progressMonitor = new ProgressMonitor(this, "Computing " + theData.getToBeCompleted() + " values of D prime","", 0, theData.getToBeCompleted()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2000); final SwingWorker worker = new SwingWorker(){ public Object construct(){ theData.doMonitoredComputation(); return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ progressMonitor.setProgress(theData.getComplete()); if (theData.finished){ timer.stop(); progressMonitor.close(); infoKnown=false; drawPicture(theData); loadInfoMenuItem.setEnabled(true); hapMenuItem.setEnabled(true); customizeHapsMenuItem.setEnabled(true); exportMenuItem.setEnabled(true); saveDprimeMenuItem.setEnabled(true); clearBlocksMenuItem.setEnabled(true); guessBlocksMenuItem.setEnabled(true); } } }); worker.start(); timer.start(); }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); } } } else if (command == loadInfoStr){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ int good = theData.prepareMarkerInput(fc.getSelectedFile()); 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; // loadInfoMenuItem.setEnabled(false); drawPicture(theData); } }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); } } }else if (command == "Clear All Blocks"){ theBlocks.clearBlocks(); }else if (command == "Define Blocks"){ defineBlocks(); }else if (command == "Customize Haplotype Output"){ customizeHaps(); }else if (command == "Tutorial"){ showHelp(); }else if (command == "Export LD Picture to JPG"){ doExportDPrime(); }else if (command == "Dump LD Output to Text"){ saveDprimeToText(); }else if (command == "Save Haplotypes to Text"){ saveHapsToText(); }else if (command == "Save Haplotypes to JPG"){ saveHapsPic(); }else if (command == "Generate Haplotypes"){ try{ drawHaplos(theData.generateHaplotypes(theData.blocks, haploThresh)); saveHapsMenuItem.setEnabled(true); saveHapsPicMenuItem.setEnabled(true); }catch (IOException ioe){} } else if (command == "Exit"){ System.exit(0); } } |
File inputFile = fc.getSelectedFile(); if (command == "Open Linkage File"){ JFrame checkWindow = new JFrame(); CheckDataPanel checkPanel = new CheckDataPanel(inputFile); checkWindow.setTitle("Checking markers..."); checkWindow.add(checkPanel); checkWindow.add(new JButton("FOO")); checkWindow.pack(); checkWindow.setVisible(true); } | shortHapInputFileName = fc.getSelectedFile().getName(); | public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Open Haplotype File" || command == "Open Linkage File"){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File inputFile = fc.getSelectedFile(); if (command == "Open Linkage File"){ //pop open checkdata window JFrame checkWindow = new JFrame(); CheckDataPanel checkPanel = new CheckDataPanel(inputFile); checkWindow.setTitle("Checking markers..."); checkWindow.add(checkPanel); checkWindow.add(new JButton("FOO")); checkWindow.pack(); checkWindow.setVisible(true); } try{ theData = new HaploData(inputFile); infileName = inputFile.getName(); //compute D primes and monitor progress progressMonitor = new ProgressMonitor(this, "Computing " + theData.getToBeCompleted() + " values of D prime","", 0, theData.getToBeCompleted()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2000); final SwingWorker worker = new SwingWorker(){ public Object construct(){ theData.doMonitoredComputation(); return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ progressMonitor.setProgress(theData.getComplete()); if (theData.finished){ timer.stop(); progressMonitor.close(); infoKnown=false; drawPicture(theData); loadInfoMenuItem.setEnabled(true); hapMenuItem.setEnabled(true); customizeHapsMenuItem.setEnabled(true); exportMenuItem.setEnabled(true); saveDprimeMenuItem.setEnabled(true); clearBlocksMenuItem.setEnabled(true); guessBlocksMenuItem.setEnabled(true); } } }); worker.start(); timer.start(); }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); } } } else if (command == loadInfoStr){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ int good = theData.prepareMarkerInput(fc.getSelectedFile()); 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; // loadInfoMenuItem.setEnabled(false); drawPicture(theData); } }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); } } }else if (command == "Clear All Blocks"){ theBlocks.clearBlocks(); }else if (command == "Define Blocks"){ defineBlocks(); }else if (command == "Customize Haplotype Output"){ customizeHaps(); }else if (command == "Tutorial"){ showHelp(); }else if (command == "Export LD Picture to JPG"){ doExportDPrime(); }else if (command == "Dump LD Output to Text"){ saveDprimeToText(); }else if (command == "Save Haplotypes to Text"){ saveHapsToText(); }else if (command == "Save Haplotypes to JPG"){ saveHapsPic(); }else if (command == "Generate Haplotypes"){ try{ drawHaplos(theData.generateHaplotypes(theData.blocks, haploThresh)); saveHapsMenuItem.setEnabled(true); saveHapsPicMenuItem.setEnabled(true); }catch (IOException ioe){} } else if (command == "Exit"){ System.exit(0); } } |
theData = new HaploData(inputFile); infileName = inputFile.getName(); progressMonitor = new ProgressMonitor(this, "Computing " + theData.getToBeCompleted() + " values of D prime","", 0, theData.getToBeCompleted()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2000); final SwingWorker worker = new SwingWorker(){ public Object construct(){ theData.doMonitoredComputation(); return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ progressMonitor.setProgress(theData.getComplete()); if (theData.finished){ timer.stop(); progressMonitor.close(); infoKnown=false; drawPicture(theData); loadInfoMenuItem.setEnabled(true); hapMenuItem.setEnabled(true); customizeHapsMenuItem.setEnabled(true); exportMenuItem.setEnabled(true); saveDprimeMenuItem.setEnabled(true); clearBlocksMenuItem.setEnabled(true); guessBlocksMenuItem.setEnabled(true); } } }); worker.start(); timer.start(); | hapInputFileName = fc.getSelectedFile().getCanonicalPath(); | public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Open Haplotype File" || command == "Open Linkage File"){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File inputFile = fc.getSelectedFile(); if (command == "Open Linkage File"){ //pop open checkdata window JFrame checkWindow = new JFrame(); CheckDataPanel checkPanel = new CheckDataPanel(inputFile); checkWindow.setTitle("Checking markers..."); checkWindow.add(checkPanel); checkWindow.add(new JButton("FOO")); checkWindow.pack(); checkWindow.setVisible(true); } try{ theData = new HaploData(inputFile); infileName = inputFile.getName(); //compute D primes and monitor progress progressMonitor = new ProgressMonitor(this, "Computing " + theData.getToBeCompleted() + " values of D prime","", 0, theData.getToBeCompleted()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2000); final SwingWorker worker = new SwingWorker(){ public Object construct(){ theData.doMonitoredComputation(); return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ progressMonitor.setProgress(theData.getComplete()); if (theData.finished){ timer.stop(); progressMonitor.close(); infoKnown=false; drawPicture(theData); loadInfoMenuItem.setEnabled(true); hapMenuItem.setEnabled(true); customizeHapsMenuItem.setEnabled(true); exportMenuItem.setEnabled(true); saveDprimeMenuItem.setEnabled(true); clearBlocksMenuItem.setEnabled(true); guessBlocksMenuItem.setEnabled(true); } } }); worker.start(); timer.start(); }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); } } } else if (command == loadInfoStr){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ int good = theData.prepareMarkerInput(fc.getSelectedFile()); 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; // loadInfoMenuItem.setEnabled(false); drawPicture(theData); } }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); } } }else if (command == "Clear All Blocks"){ theBlocks.clearBlocks(); }else if (command == "Define Blocks"){ defineBlocks(); }else if (command == "Customize Haplotype Output"){ customizeHaps(); }else if (command == "Tutorial"){ showHelp(); }else if (command == "Export LD Picture to JPG"){ doExportDPrime(); }else if (command == "Dump LD Output to Text"){ saveDprimeToText(); }else if (command == "Save Haplotypes to Text"){ saveHapsToText(); }else if (command == "Save Haplotypes to JPG"){ saveHapsPic(); }else if (command == "Generate Haplotypes"){ try{ drawHaplos(theData.generateHaplotypes(theData.blocks, haploThresh)); saveHapsMenuItem.setEnabled(true); saveHapsPicMenuItem.setEnabled(true); }catch (IOException ioe){} } else if (command == "Exit"){ System.exit(0); } } |
}catch (RuntimeException rtexec){ JOptionPane.showMessageDialog(this, "An error has occured. It is probably related to file format:\n"+rtexec.toString(), "Error", JOptionPane.ERROR_MESSAGE); | public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Open Haplotype File" || command == "Open Linkage File"){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File inputFile = fc.getSelectedFile(); if (command == "Open Linkage File"){ //pop open checkdata window JFrame checkWindow = new JFrame(); CheckDataPanel checkPanel = new CheckDataPanel(inputFile); checkWindow.setTitle("Checking markers..."); checkWindow.add(checkPanel); checkWindow.add(new JButton("FOO")); checkWindow.pack(); checkWindow.setVisible(true); } try{ theData = new HaploData(inputFile); infileName = inputFile.getName(); //compute D primes and monitor progress progressMonitor = new ProgressMonitor(this, "Computing " + theData.getToBeCompleted() + " values of D prime","", 0, theData.getToBeCompleted()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2000); final SwingWorker worker = new SwingWorker(){ public Object construct(){ theData.doMonitoredComputation(); return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ progressMonitor.setProgress(theData.getComplete()); if (theData.finished){ timer.stop(); progressMonitor.close(); infoKnown=false; drawPicture(theData); loadInfoMenuItem.setEnabled(true); hapMenuItem.setEnabled(true); customizeHapsMenuItem.setEnabled(true); exportMenuItem.setEnabled(true); saveDprimeMenuItem.setEnabled(true); clearBlocksMenuItem.setEnabled(true); guessBlocksMenuItem.setEnabled(true); } } }); worker.start(); timer.start(); }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); } } } else if (command == loadInfoStr){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ int good = theData.prepareMarkerInput(fc.getSelectedFile()); 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; // loadInfoMenuItem.setEnabled(false); drawPicture(theData); } }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); } } }else if (command == "Clear All Blocks"){ theBlocks.clearBlocks(); }else if (command == "Define Blocks"){ defineBlocks(); }else if (command == "Customize Haplotype Output"){ customizeHaps(); }else if (command == "Tutorial"){ showHelp(); }else if (command == "Export LD Picture to JPG"){ doExportDPrime(); }else if (command == "Dump LD Output to Text"){ saveDprimeToText(); }else if (command == "Save Haplotypes to Text"){ saveHapsToText(); }else if (command == "Save Haplotypes to JPG"){ saveHapsPic(); }else if (command == "Generate Haplotypes"){ try{ drawHaplos(theData.generateHaplotypes(theData.blocks, haploThresh)); saveHapsMenuItem.setEnabled(true); saveHapsPicMenuItem.setEnabled(true); }catch (IOException ioe){} } else if (command == "Exit"){ System.exit(0); } } |
|
}else if (command == "Export LD Picture to JPG"){ | }else if (command == "Export LD Picture to PNG"){ | public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Open Haplotype File" || command == "Open Linkage File"){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File inputFile = fc.getSelectedFile(); if (command == "Open Linkage File"){ //pop open checkdata window JFrame checkWindow = new JFrame(); CheckDataPanel checkPanel = new CheckDataPanel(inputFile); checkWindow.setTitle("Checking markers..."); checkWindow.add(checkPanel); checkWindow.add(new JButton("FOO")); checkWindow.pack(); checkWindow.setVisible(true); } try{ theData = new HaploData(inputFile); infileName = inputFile.getName(); //compute D primes and monitor progress progressMonitor = new ProgressMonitor(this, "Computing " + theData.getToBeCompleted() + " values of D prime","", 0, theData.getToBeCompleted()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2000); final SwingWorker worker = new SwingWorker(){ public Object construct(){ theData.doMonitoredComputation(); return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ progressMonitor.setProgress(theData.getComplete()); if (theData.finished){ timer.stop(); progressMonitor.close(); infoKnown=false; drawPicture(theData); loadInfoMenuItem.setEnabled(true); hapMenuItem.setEnabled(true); customizeHapsMenuItem.setEnabled(true); exportMenuItem.setEnabled(true); saveDprimeMenuItem.setEnabled(true); clearBlocksMenuItem.setEnabled(true); guessBlocksMenuItem.setEnabled(true); } } }); worker.start(); timer.start(); }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); } } } else if (command == loadInfoStr){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ int good = theData.prepareMarkerInput(fc.getSelectedFile()); 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; // loadInfoMenuItem.setEnabled(false); drawPicture(theData); } }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); } } }else if (command == "Clear All Blocks"){ theBlocks.clearBlocks(); }else if (command == "Define Blocks"){ defineBlocks(); }else if (command == "Customize Haplotype Output"){ customizeHaps(); }else if (command == "Tutorial"){ showHelp(); }else if (command == "Export LD Picture to JPG"){ doExportDPrime(); }else if (command == "Dump LD Output to Text"){ saveDprimeToText(); }else if (command == "Save Haplotypes to Text"){ saveHapsToText(); }else if (command == "Save Haplotypes to JPG"){ saveHapsPic(); }else if (command == "Generate Haplotypes"){ try{ drawHaplos(theData.generateHaplotypes(theData.blocks, haploThresh)); saveHapsMenuItem.setEnabled(true); saveHapsPicMenuItem.setEnabled(true); }catch (IOException ioe){} } else if (command == "Exit"){ System.exit(0); } } |
}else if (command == "Save Haplotypes to JPG"){ | }else if (command == "Save Haplotypes to PNG"){ | public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Open Haplotype File" || command == "Open Linkage File"){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File inputFile = fc.getSelectedFile(); if (command == "Open Linkage File"){ //pop open checkdata window JFrame checkWindow = new JFrame(); CheckDataPanel checkPanel = new CheckDataPanel(inputFile); checkWindow.setTitle("Checking markers..."); checkWindow.add(checkPanel); checkWindow.add(new JButton("FOO")); checkWindow.pack(); checkWindow.setVisible(true); } try{ theData = new HaploData(inputFile); infileName = inputFile.getName(); //compute D primes and monitor progress progressMonitor = new ProgressMonitor(this, "Computing " + theData.getToBeCompleted() + " values of D prime","", 0, theData.getToBeCompleted()); progressMonitor.setProgress(0); progressMonitor.setMillisToDecideToPopup(2000); final SwingWorker worker = new SwingWorker(){ public Object construct(){ theData.doMonitoredComputation(); return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ progressMonitor.setProgress(theData.getComplete()); if (theData.finished){ timer.stop(); progressMonitor.close(); infoKnown=false; drawPicture(theData); loadInfoMenuItem.setEnabled(true); hapMenuItem.setEnabled(true); customizeHapsMenuItem.setEnabled(true); exportMenuItem.setEnabled(true); saveDprimeMenuItem.setEnabled(true); clearBlocksMenuItem.setEnabled(true); guessBlocksMenuItem.setEnabled(true); } } }); worker.start(); timer.start(); }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); } } } else if (command == loadInfoStr){ fc.setSelectedFile(null); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ int good = theData.prepareMarkerInput(fc.getSelectedFile()); 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; // loadInfoMenuItem.setEnabled(false); drawPicture(theData); } }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); } } }else if (command == "Clear All Blocks"){ theBlocks.clearBlocks(); }else if (command == "Define Blocks"){ defineBlocks(); }else if (command == "Customize Haplotype Output"){ customizeHaps(); }else if (command == "Tutorial"){ showHelp(); }else if (command == "Export LD Picture to JPG"){ doExportDPrime(); }else if (command == "Dump LD Output to Text"){ saveDprimeToText(); }else if (command == "Save Haplotypes to Text"){ saveHapsToText(); }else if (command == "Save Haplotypes to JPG"){ saveHapsPic(); }else if (command == "Generate Haplotypes"){ try{ drawHaplos(theData.generateHaplotypes(theData.blocks, haploThresh)); saveHapsMenuItem.setEnabled(true); saveHapsPicMenuItem.setEnabled(true); }catch (IOException ioe){} } else if (command == "Exit"){ System.exit(0); } } |
"Four Gamete Rule", | void defineBlocks(){ String[] methodStrings = {"95% of informative pairwise comparisons show strong LD via confidence intervals (SFS)", "Solid block of strong LD via D prime (MJD)"}; JComboBox methodList = new JComboBox(methodStrings); JOptionPane.showMessageDialog(window, methodList, "Select a block-finding algorithm", JOptionPane.QUESTION_MESSAGE); theData.blocks = theData.guessBlocks(theData.dPrimeTable, methodList.getSelectedIndex()); drawPicture(theData); } |
|
checkPanel = new CheckDataPanel(theData); | checkPanel = new CheckDataPanel(theData, true); | 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); 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); } } |
checkPanel = new CheckDataPanel(theData); | checkPanel = new CheckDataPanel(theData, true); | void readMarkers(File inputFile, String[][] hminfo){ try { theData.prepareMarkerInput(inputFile, maxCompDist, hminfo); if (theData.infoKnown){ analysisItem.setEnabled(true); }else{ analysisItem.setEnabled(false); } if (checkPanel != null){ //this is triggered when loading markers after already loading genotypes //it is dumb and sucks, but at least it works. bah. checkPanel = new CheckDataPanel(theData); Container checkTab = (Container)tabs.getComponentAt(VIEW_CHECK_NUM); checkTab.removeAll(); 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); checkTab.add(metaCheckPanel); repaint(); } if (tdtPanel != null){ tdtPanel.refreshNames(); } }catch (HaploViewException e){ JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (PedFileException pfe){ } } |
suite.addTestSuite(TestSQLColumn.class); | suite.addTest(TestSQLColumn.suite()); | public static Test suite() { TestSuite suite = new TestSuite("Test for regress"); //$JUnit-BEGIN$ suite.addTestSuite(TestSQLDatabase.class); suite.addTestSuite(ArchitectExceptionTest.class); suite.addTestSuite(SaveLoadTest.class); suite.addTestSuite(PLDotIniTest.class); suite.addTestSuite(TestSQLColumn.class); suite.addTestSuite(JDBCClassLoaderTest.class); suite.addTestSuite(LogWriterTest.class); suite.addTestSuite(TestDDLUtils.class); suite.addTestSuite(SQLObjectTest.class); suite.addTestSuite(TestSQLTable.class); suite.addTestSuite(TestSQLRelationship.class); //$JUnit-END$ return suite; } |
suite.addTestSuite(TestArchitectDataSource.class); | public static Test suite() { TestSuite suite = new TestSuite("Test for regress"); //$JUnit-BEGIN$ suite.addTestSuite(TestSQLDatabase.class); suite.addTestSuite(ArchitectExceptionTest.class); suite.addTestSuite(SaveLoadTest.class); suite.addTestSuite(PLDotIniTest.class); suite.addTestSuite(TestSQLColumn.class); suite.addTestSuite(JDBCClassLoaderTest.class); suite.addTestSuite(LogWriterTest.class); suite.addTestSuite(TestDDLUtils.class); suite.addTestSuite(SQLObjectTest.class); suite.addTestSuite(TestSQLTable.class); suite.addTestSuite(TestSQLRelationship.class); //$JUnit-END$ return suite; } |
|
PhotoInfo photo2 = null; try { photo2 = PhotoInfo.retrievePhotoInfo( photo.getUid() ); } catch( PhotoNotFoundException e ) { fail( "Photo not storein into DB" ); } foundThumbnail = false; ImageInstance thumbnail2 = null; for ( int n = 0; n < instanceCount+1; n++ ) { ImageInstance instance = photo2.getInstance( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_THUMBNAIL ) { foundThumbnail = true; thumbnail2 = instance; break; } } assertTrue( "Could not find the created thumbnail", foundThumbnail ); assertEquals( "Thumbnail width should be 100", 100, thumbnail2.getWidth() ); assertTrue( "Thumbnail filename not saved correctly", thumbnailFile.equals( thumbnail2.getImageFile() )); | public void testThumbnailCreate() { String testImgDir = "c:\\java\\photovault\\testfiles"; String fname = "test1.jpg"; File f = new File( testImgDir, fname ); PhotoInfo photo = null; try { photo = PhotoInfo.addToDB( f ); } catch ( PhotoNotFoundException e ) { fail( "Could not find photo: " + e.getMessage() ); } assertNotNull( photo ); int instanceCount = photo.getNumInstances(); photo.createThumbnail(); assertEquals( "InstanceNum should be 1 greater after adding thumbnail", instanceCount+1, photo.getNumInstances() ); // Try to find the new thumbnail boolean foundThumbnail = false; ImageInstance thumbnail = null; for ( int n = 0; n < instanceCount+1; n++ ) { ImageInstance instance = photo.getInstance( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_THUMBNAIL ) { foundThumbnail = true; thumbnail = instance; break; } } assertTrue( "Could not find the created thumbnail", foundThumbnail ); assertEquals( "Thumbnail width should be 100", 100, thumbnail.getWidth() ); File thumbnailFile = thumbnail.getImageFile(); assertTrue( "Image file does not exist", thumbnailFile.exists() ); // Test the getThumbnail method Thumbnail thumb = photo.getThumbnail(); assertNotNull( thumb ); assertFalse( "Thumbnail exists, should not return default thumbnail", thumb == Thumbnail.getDefaultThumbnail() ); assertEquals( "Thumbnail exists, getThumbnail should not create a new instance", instanceCount+1, photo.getNumInstances() ); photo.delete(); assertFalse( "Image file does exist after delete", thumbnailFile.exists() ); } |
|
public Tag createTag() { | public Tag createTag(String name, Attributes attributes) { | public void doTag(XMLOutput output) throws Exception { invokeBody(output); if (name == null) { throw new MissingAttributeException("name"); } if (className == null) { throw new MissingAttributeException("className"); } Class theClass = null; try { ClassLoader classLoader = getClassLoader(); theClass = classLoader.loadClass(className); } catch (ClassNotFoundException e) { try { theClass = getClass().getClassLoader().loadClass(className); } catch (ClassNotFoundException e2) { try { theClass = Class.forName(className); } catch (ClassNotFoundException e3) { log.error( "Could not load class: " + className + " exception: " + e, e ); throw new JellyException( "Could not find class: " + className + " using ClassLoader: " + classLoader); } } } final Class beanClass = theClass; final Method invokeMethod = getInvokeMethod( theClass ); final Map beanAttributes = (attributes != null) ? attributes : EMPTY_MAP; TagFactory factory = new TagFactory() { public Tag createTag() { return new DynamicBeanTag(beanClass, beanAttributes, varAttribute, invokeMethod); } }; getTagLibrary().registerBeanTag(name, factory); // now lets clear the attributes for next invocation and help the GC attributes = null; } |
public Tag createTag() { | public Tag createTag(String name, Attributes attributes) { | public Tag createTag() { return new DynamicBeanTag(beanClass, beanAttributes, varAttribute, invokeMethod); } |
Context context = new Context(); | JellyContext context = new JellyContext(); | public void testArgs() throws Exception { InputStream in = getClass().getResourceAsStream( "testing123.jelly" ); XMLParser parser = new XMLParser(); Script script = parser.parse( in ); script = script.compile(); log.debug( "Found: " + script ); assertTrue( "Script is a TagScript", script instanceof TagScript ); String[] args = { "one", "two", "three" }; Context context = new Context(); context.setVariable( "args", args ); StringWriter buffer = new StringWriter(); script.run( context, XMLOutput.createXMLOutput( buffer ) ); String text = buffer.toString().trim(); if ( log.isDebugEnabled() ) { log.debug( "Evaluated script as..." ); log.debug( text ); } assertEquals( "Produces the correct output", "one two three", text ); } |
ArchitectSession.getInstance().addDriverJar(path); | ArchitectSessionImpl.getInstance().addDriverJar(path); | public void addDriverJarPath(String path) { ArchitectSession.getInstance().addDriverJar(path); } |
SwingUtilities.invokeLater( new Runnable(){ public void run() { genoFileField.requestFocus(); } }); | genoFileField.requestFocus(); genoFileField.dispatchEvent( new FocusEvent( genoFileField, FocusEvent.FOCUS_GAINED, false ) ); | void load(int ft){ fileType = ft; JPanel contents = new JPanel(); contents.setLayout(new BoxLayout(contents, BoxLayout.Y_AXIS)); JPanel filePanel = new JPanel(); filePanel.setLayout(new BoxLayout(filePanel, BoxLayout.Y_AXIS)); JPanel topFilePanel = new JPanel(); JPanel botFilePanel = new JPanel(); genoFileField = new JTextField("",20); //workaround for stupid java problem where focus can't be granted until window is displayed //TODO: appears to throw an exception in Linux SwingUtilities.invokeLater( new Runnable(){ public void run() { genoFileField.requestFocus(); } }); infoFileField = new JTextField("",20); JButton browseGenoButton = new JButton("Browse"); browseGenoButton.setActionCommand(BROWSE_GENO); browseGenoButton.addActionListener(this); JButton browseInfoButton = new JButton("Browse"); browseInfoButton.setActionCommand(BROWSE_INFO); browseInfoButton.addActionListener(this); topFilePanel.add(new JLabel("Genotype file: ")); topFilePanel.add(genoFileField); topFilePanel.add(browseGenoButton); botFilePanel.add(new JLabel("Locus information file: ")); botFilePanel.add(infoFileField); botFilePanel.add(browseInfoButton); filePanel.add(topFilePanel); filePanel.add(botFilePanel); filePanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); contents.add(filePanel); JPanel prefsPanel = new JPanel(); maxComparisonDistField = new NumberTextField("500",4); prefsPanel.add(new JLabel("Ignore pairwise comparisons of markers >")); prefsPanel.add(maxComparisonDistField); prefsPanel.add(new JLabel("kb apart.")); contents.add(prefsPanel); JPanel choicePanel = new JPanel(); JButton okButton = new JButton("OK"); this.getRootPane().setDefaultButton(okButton); okButton.addActionListener(this); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(this); choicePanel.add(okButton); choicePanel.add(cancelButton); contents.add(choicePanel); this.setContentPane(contents); this.pack(); } |
boolean startPDP = printDPrimeValues; boolean startPMN = printMarkerNames; | boolean startPD = printDPrimeValues; boolean startMN = printMarkerNames; int startZL = zoomLevel; | public BufferedImage export(int start, int stop, boolean compress){ forExport = true; exportStart = start; if (exportStart < 0){ exportStart = 0; } exportStop = stop; if (exportStop > Chromosome.getSize()){ exportStop = Chromosome.getSize(); } int startBS = boxSize; int startBR = boxRadius; boolean startPDP = printDPrimeValues; boolean startPMN = printMarkerNames; if (compress){ printDPrimeValues = false; printMarkerNames = false; if (boxSize > (1200/(stop - start))){ boxSize = 1200/(stop - start); if (boxSize < 2){ boxSize = 2; } //to make picture not look dumb we need to avoid odd numbers for really teeny boxes if (boxSize < 10){ if (boxSize%2 != 0){ boxSize++; } } boxRadius = boxSize/2; } } Dimension pref = getPreferredSize(); BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); boxSize = startBS; boxRadius = startBR; printDPrimeValues = startPDP; printMarkerNames = startPMN; forExport = false; return i; } |
printDPrimeValues = startPDP; printMarkerNames = startPMN; | zoomLevel = startZL; printMarkerNames = startMN; printDPrimeValues = startPD; | public BufferedImage export(int start, int stop, boolean compress){ forExport = true; exportStart = start; if (exportStart < 0){ exportStart = 0; } exportStop = stop; if (exportStop > Chromosome.getSize()){ exportStop = Chromosome.getSize(); } int startBS = boxSize; int startBR = boxRadius; boolean startPDP = printDPrimeValues; boolean startPMN = printMarkerNames; if (compress){ printDPrimeValues = false; printMarkerNames = false; if (boxSize > (1200/(stop - start))){ boxSize = 1200/(stop - start); if (boxSize < 2){ boxSize = 2; } //to make picture not look dumb we need to avoid odd numbers for really teeny boxes if (boxSize < 10){ if (boxSize%2 != 0){ boxSize++; } } boxRadius = boxSize/2; } } Dimension pref = getPreferredSize(); BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); boxSize = startBS; boxRadius = startBR; printDPrimeValues = startPDP; printMarkerNames = startPMN; forExport = false; return i; } |
this.computePreferredSize(); | public BufferedImage export(int start, int stop, boolean compress){ forExport = true; exportStart = start; if (exportStart < 0){ exportStart = 0; } exportStop = stop; if (exportStop > Chromosome.getSize()){ exportStop = Chromosome.getSize(); } int startBS = boxSize; int startBR = boxRadius; boolean startPDP = printDPrimeValues; boolean startPMN = printMarkerNames; if (compress){ printDPrimeValues = false; printMarkerNames = false; if (boxSize > (1200/(stop - start))){ boxSize = 1200/(stop - start); if (boxSize < 2){ boxSize = 2; } //to make picture not look dumb we need to avoid odd numbers for really teeny boxes if (boxSize < 10){ if (boxSize%2 != 0){ boxSize++; } } boxRadius = boxSize/2; } } Dimension pref = getPreferredSize(); BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); boxSize = startBS; boxRadius = startBR; printDPrimeValues = startPDP; printMarkerNames = startPMN; forExport = false; return i; } |
|
logWriter = new PrintWriter(new FileWriter(USER_ACTIVITY_LOG_FILE_NAME, true)); | File logDir = new File(CoreUtils.getLogDir()); logDir.mkdir(); File logFile = new File(logDir.getPath() + File.separatorChar + USER_ACTIVITY_LOG_FILE_NAME); logWriter = new PrintWriter(new FileWriter(logFile, true)); | private UserActivityLogger(){ super(); activities = new Vector(); activityBuffer = new Vector(); /* Open the file to write, and set it to append all new entries */ try{ logWriter = new PrintWriter(new FileWriter(USER_ACTIVITY_LOG_FILE_NAME, true)); }catch (IOException ioe){ ioe.printStackTrace(); } } |
JButton closeButton = new JButton(closeAction); | JDefaultButton closeButton = new JDefaultButton(closeAction); | public void doStuff() { if (isCancelled()) return; // now implements Monitorable, so we can ask it how it's doing try { plExport.export(playpen.getDatabase()); // if the user requested, try running the PL Job afterwards if (plExport.getRunPLEngine()) { logger.debug("Running PL Engine"); File plEngine = new File(architectFrame.getUserSettings().getETLUserSettings().getPowerLoaderEnginePath()); File plDir = plEngine.getParentFile(); File engineExe = new File(plDir, PLUtils.getEngineExecutableName(plExport.getRepositoryDataSource())); final StringBuffer commandLine = new StringBuffer(1000); commandLine.append(engineExe.getPath()); commandLine.append(" USER_PROMPT=N"); commandLine.append(" JOB=").append(plExport.getJobId()); commandLine.append(" USER=").append(PLUtils.getEngineConnectString(plExport.getRepositoryDataSource())); commandLine.append(" DEBUG=N SEND_EMAIL=N SKIP_PACKAGES=N CALC_DETAIL_STATS=N COMMIT_FREQ=100 APPEND_TO_JOB_LOG_IND=N"); commandLine.append(" APPEND_TO_JOB_ERR_IND=N"); commandLine.append(" SHOW_PROGRESS=100" ); commandLine.append(" SHOW_PROGRESS=10" ); logger.debug(commandLine.toString()); // worker thread must not talk to Swing directly... SwingUtilities.invokeLater(new Runnable() { public void run() { try { final Process proc = Runtime.getRuntime().exec(commandLine.toString()); // Could in theory make this use ArchitectPanelBuilder, by creating // a JPanel subclass, but may not be worthwhile as it has both an // Abort and a Close button... final JDialog pld = new JDialog(architectFrame, "Power*Loader Engine"); EngineExecPanel eep = new EngineExecPanel(commandLine.toString(), proc); pld.setContentPane(eep); Action closeAction = new CommonCloseAction(pld); JButton abortButton = new JButton(eep.getAbortAction()); JButton closeButton = new JButton(closeAction); JCheckBox scrollLockCheckBox = new JCheckBox(eep.getScrollBarLockAction()); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); buttonPanel.add(abortButton); buttonPanel.add(closeButton); buttonPanel.add(scrollLockCheckBox); eep.add(buttonPanel, BorderLayout.SOUTH); // XXX what should "<Escape> do to a dialog that has // both an Abort and a Close button?? // ArchitectPanelBuilder.makeJDialogCancellable(pld, // eep.getAbortAction(), closeAction); pld.getRootPane().setDefaultButton(closeButton); pld.pack(); pld.setLocationRelativeTo(d); pld.setVisible(true); } catch (IOException ie){ JOptionPane.showMessageDialog(architectFrame, "Unexpected Exception running Engine:\n"+ie); logger.error("IOException while trying to run engine.",ie); } } }); } } catch (PLSecurityException ex) { final Exception fex = ex; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+fex.getMessage()); logger.error("Got exception while exporting Trans", fex); } }); } catch (SQLException esql) { final Exception fesql = esql; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+fesql.getMessage()); logger.error("Got exception while exporting Trans", fesql); } }); } catch (ArchitectException arex){ final Exception farex = arex; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+farex.getMessage()); logger.error("Got exception while exporting Trans", farex); } }); } } |
JButton closeButton = new JButton(closeAction); | JDefaultButton closeButton = new JDefaultButton(closeAction); | public void run() { try { final Process proc = Runtime.getRuntime().exec(commandLine.toString()); // Could in theory make this use ArchitectPanelBuilder, by creating // a JPanel subclass, but may not be worthwhile as it has both an // Abort and a Close button... final JDialog pld = new JDialog(architectFrame, "Power*Loader Engine"); EngineExecPanel eep = new EngineExecPanel(commandLine.toString(), proc); pld.setContentPane(eep); Action closeAction = new CommonCloseAction(pld); JButton abortButton = new JButton(eep.getAbortAction()); JButton closeButton = new JButton(closeAction); JCheckBox scrollLockCheckBox = new JCheckBox(eep.getScrollBarLockAction()); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); buttonPanel.add(abortButton); buttonPanel.add(closeButton); buttonPanel.add(scrollLockCheckBox); eep.add(buttonPanel, BorderLayout.SOUTH); // XXX what should "<Escape> do to a dialog that has // both an Abort and a Close button?? // ArchitectPanelBuilder.makeJDialogCancellable(pld, // eep.getAbortAction(), closeAction); pld.getRootPane().setDefaultButton(closeButton); pld.pack(); pld.setLocationRelativeTo(d); pld.setVisible(true); } catch (IOException ie){ JOptionPane.showMessageDialog(architectFrame, "Unexpected Exception running Engine:\n"+ie); logger.error("IOException while trying to run engine.",ie); } } |
context.removeVariable(var); | context.removeVariable( var.evaluateAsString(context) ); | public void doTag(XMLOutput output) throws MissingAttributeException { if (var != null) { context.removeVariable(var); } else { throw new MissingAttributeException("var"); } } |
public void setVar(String var) { | public void setVar(Expression var) { | public void setVar(String var) { this.var = var; } |
if ( firstRun ) { firstRun = false; tag = findDynamicTag(context, (StaticTag) tag); } | tag = findDynamicTag(context, (StaticTag) tag); | public void run(JellyContext context, XMLOutput output) throws Exception { startNamespacePrefixes(output); Tag tag = getTag(); if ( firstRun ) { firstRun = false; // 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); } |
}else if("I".equals(user.getStatus())){ | }else if(User.STATUS_LOCKED.equals(user.getStatus())){ | public void login(ServiceContext context, String username, String password) throws ServiceException{ LoginCallbackHandler callbackHandler = new LoginCallbackHandler(); callbackHandler.setUsername(username); callbackHandler.setPassword(password); User user = null; UserManager userManager = UserManager.getInstance(); UserActivityLogger logger = UserActivityLogger.getInstance(); try{ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, callbackHandler); loginContext.login(); /* set Subject in session */ context._setSubject(loginContext.getSubject()); /* Successful login: update the lock count and status */ user = userManager.getUser(username); user.setLockCount(0); user.setStatus(null); userManager.updateUser(user); logger.logActivity(username, "logged in successfully"); }catch(LoginException lex){ user = userManager.getUser(username); String errorCode = ErrorCodes.UNKNOWN_ERROR; Object[] values = null; /* Conditionalize the error message */ if(user == null){ errorCode = ErrorCodes.INVALID_CREDENTIALS; }else if("I".equals(user.getStatus())){ errorCode = ErrorCodes.ACCOUNT_LOCKED; }else if(user.getLockCount() < MAX_LOGIN_ATTEMPTS_ALLOWED){ int thisAttempt = user.getLockCount()+1; user.setLockCount(thisAttempt); if(thisAttempt == MAX_LOGIN_ATTEMPTS_ALLOWED){ user.setStatus("I"); userManager.updateUser(user); errorCode = ErrorCodes.ACCOUNT_LOCKED; }else{ userManager.updateUser(user); errorCode = ErrorCodes.INVALID_LOGIN_ATTEMPTS; values = new Object[]{ String.valueOf(MAX_LOGIN_ATTEMPTS_ALLOWED - thisAttempt)}; } } logger.logActivity(username, user.getName()+" failed to login"); throw new ServiceException(errorCode, values); } } |
user.setStatus("I"); | user.setStatus(User.STATUS_LOCKED); | public void login(ServiceContext context, String username, String password) throws ServiceException{ LoginCallbackHandler callbackHandler = new LoginCallbackHandler(); callbackHandler.setUsername(username); callbackHandler.setPassword(password); User user = null; UserManager userManager = UserManager.getInstance(); UserActivityLogger logger = UserActivityLogger.getInstance(); try{ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, callbackHandler); loginContext.login(); /* set Subject in session */ context._setSubject(loginContext.getSubject()); /* Successful login: update the lock count and status */ user = userManager.getUser(username); user.setLockCount(0); user.setStatus(null); userManager.updateUser(user); logger.logActivity(username, "logged in successfully"); }catch(LoginException lex){ user = userManager.getUser(username); String errorCode = ErrorCodes.UNKNOWN_ERROR; Object[] values = null; /* Conditionalize the error message */ if(user == null){ errorCode = ErrorCodes.INVALID_CREDENTIALS; }else if("I".equals(user.getStatus())){ errorCode = ErrorCodes.ACCOUNT_LOCKED; }else if(user.getLockCount() < MAX_LOGIN_ATTEMPTS_ALLOWED){ int thisAttempt = user.getLockCount()+1; user.setLockCount(thisAttempt); if(thisAttempt == MAX_LOGIN_ATTEMPTS_ALLOWED){ user.setStatus("I"); userManager.updateUser(user); errorCode = ErrorCodes.ACCOUNT_LOCKED; }else{ userManager.updateUser(user); errorCode = ErrorCodes.INVALID_LOGIN_ATTEMPTS; values = new Object[]{ String.valueOf(MAX_LOGIN_ATTEMPTS_ALLOWED - thisAttempt)}; } } logger.logActivity(username, user.getName()+" failed to login"); throw new ServiceException(errorCode, values); } } |
logger.logActivity(username, user.getName()+" failed to login"); | if(user != null) logger.logActivity(username, user.getName()+" failed to login"); | public void login(ServiceContext context, String username, String password) throws ServiceException{ LoginCallbackHandler callbackHandler = new LoginCallbackHandler(); callbackHandler.setUsername(username); callbackHandler.setPassword(password); User user = null; UserManager userManager = UserManager.getInstance(); UserActivityLogger logger = UserActivityLogger.getInstance(); try{ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, callbackHandler); loginContext.login(); /* set Subject in session */ context._setSubject(loginContext.getSubject()); /* Successful login: update the lock count and status */ user = userManager.getUser(username); user.setLockCount(0); user.setStatus(null); userManager.updateUser(user); logger.logActivity(username, "logged in successfully"); }catch(LoginException lex){ user = userManager.getUser(username); String errorCode = ErrorCodes.UNKNOWN_ERROR; Object[] values = null; /* Conditionalize the error message */ if(user == null){ errorCode = ErrorCodes.INVALID_CREDENTIALS; }else if("I".equals(user.getStatus())){ errorCode = ErrorCodes.ACCOUNT_LOCKED; }else if(user.getLockCount() < MAX_LOGIN_ATTEMPTS_ALLOWED){ int thisAttempt = user.getLockCount()+1; user.setLockCount(thisAttempt); if(thisAttempt == MAX_LOGIN_ATTEMPTS_ALLOWED){ user.setStatus("I"); userManager.updateUser(user); errorCode = ErrorCodes.ACCOUNT_LOCKED; }else{ userManager.updateUser(user); errorCode = ErrorCodes.INVALID_LOGIN_ATTEMPTS; values = new Object[]{ String.valueOf(MAX_LOGIN_ATTEMPTS_ALLOWED - thisAttempt)}; } } logger.logActivity(username, user.getName()+" failed to login"); throw new ServiceException(errorCode, values); } } |
rs.close(); rs = null; | public void populate() throws ArchitectException { if (populated) return; int oldSize = children.size(); synchronized (parent) { ResultSet rs = null; try { Connection con = ((SQLDatabase)parent).getConnection(); DatabaseMetaData dbmd = con.getMetaData(); con.setCatalog(catalogName); rs = dbmd.getSchemas(); while (rs.next()) { String schName = rs.getString(1); SQLSchema schema = null; if (schName != null) { schema = new SQLSchema(this, schName, false); children.add(schema); schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); } } if ( oldSize == children.size() ) { rs = dbmd.getTables(catalogName, null, "%", new String[] {"TABLE", "VIEW"}); while (rs.next()) { children.add(new SQLTable(this, rs.getString(3), rs.getString(5), rs.getString(4), false)); } } } catch (SQLException e) { throw new ArchitectException("catalog.populate.fail", e); } finally { populated = true; int newSize = children.size(); if (newSize > oldSize) { int[] changedIndices = new int[newSize - oldSize]; for (int i = 0, n = newSize - oldSize; i < n; i++) { changedIndices[i] = oldSize + i; } fireDbChildrenInserted(changedIndices, children.subList(oldSize, newSize)); } try { if ( rs != null ) rs.close(); } catch (SQLException e2) { throw new ArchitectException("catalog.rs.close.fail", e2); } } } } |
|
JToolBar toolbar = new JToolBar(); String[] defaultZooms = { "12%", "25%", "50%", "100%", "Fit" }; JLabel zoomLabel = new JLabel( "Zoom" ); JComboBox zoomCombo = new JComboBox( defaultZooms ); zoomCombo.setEditable( true ); final PhotoViewer viewer = this; zoomCombo.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ev ) { JComboBox cb = (JComboBox) ev.getSource(); String selected = (String)cb.getSelectedItem(); System.out.println( "Selected: " + selected ); DecimalFormat percentFormat = new DecimalFormat( "#####.#%" ); if ( selected == "Fit" ) { System.out.println( "Fitting to window" ); fit(); float newScale = getScale(); String strNewScale = percentFormat.format( newScale ); cb.setSelectedItem( strNewScale ); } else { StringBuffer b = new StringBuffer( selected ); int spaceIndex = b.indexOf( " " ); while ( spaceIndex >= 0 ) { b.deleteCharAt( spaceIndex ); spaceIndex = b.indexOf( " " ); } selected = b.toString(); boolean success = false; float newScale = 0; try { newScale = Float.parseFloat( selected ); newScale /= 100.0; success = true; } catch (NumberFormatException e ) { } if ( !success ) { try { newScale = percentFormat.parse( selected ).floatValue(); success = true; } catch ( ParseException e ) { } } if ( success ) { System.out.println( "New scale: " + newScale ); viewer.setScale( newScale ); String strNewScale = percentFormat.format( newScale ); cb.setSelectedItem( strNewScale ); } } } }); toolbar.add( zoomLabel ); toolbar.add( zoomCombo ); add( toolbar, BorderLayout.NORTH ); | public void createUI() { imageView = new PhotoView(); scrollPane = new JScrollPane( imageView ); scrollPane.setPreferredSize( new Dimension( 500, 500 ) ); add( scrollPane, BorderLayout.CENTER ); } |
|
File f = new File("c:\\java\\photovault\\testfiles\\test1.jpg" ); try { BufferedImage bi = ImageIO.read(f); viewer.setImage( bi ); viewer.setScale( 0.3f ); System.out.println( "Succesfully loaded \""+ f.getPath() + "\"" ); } catch (IOException e ) { System.out.println( "Error loading image \""+ f.getPath() + "\"" ); | PhotoInfo photo = null; if ( args.length == 2 ) { if ( args[0].equals( "-id" ) ) { try { int id = Integer.parseInt( args[1] ); System.err.println( "Getting photo " + id ); photo = PhotoInfo.retrievePhotoInfo( id ); viewer.setPhoto( photo ); } catch ( Exception e ) { System.err.println( e.getMessage() ); e.printStackTrace(); } } | public static void main( String args[] ) { JFrame frame = new JFrame( "PhotoInfoEditorTest" ); PhotoViewer viewer = new PhotoViewer(); frame.getContentPane().add( viewer, BorderLayout.CENTER ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); File f = new File("c:\\java\\photovault\\testfiles\\test1.jpg" ); try { BufferedImage bi = ImageIO.read(f); viewer.setImage( bi ); viewer.setScale( 0.3f ); System.out.println( "Succesfully loaded \""+ f.getPath() + "\"" ); } catch (IOException e ) { System.out.println( "Error loading image \""+ f.getPath() + "\"" ); } frame.pack(); frame.setVisible( true ); } |
void setScale( float scale ) { | public void setScale( float scale ) { | void setScale( float scale ) { imageView.setScale(scale); } |
protected TagScript createStaticTag( String namespaceURI, String localName, Attributes list ) throws SAXException { | protected TagScript createStaticTag( String namespaceURI, String localName, String qName, Attributes list ) throws SAXException { | protected TagScript createStaticTag( String namespaceURI, String localName, Attributes list ) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName ); DynaTagScript script = new DynaTagScript( tag ); // now iterate through through the expressions int size = list.getLength(); for ( int i = 0; i < size; i++ ) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = getExpressionFactory().createExpression( attributeValue ); if ( expression == null ) { expression = createConstantExpression( localName, attributeName, attributeValue ); } script.addAttribute( attributeName, expression ); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e ); throw createSAXException(e); } } |
StaticTag tag = new StaticTag( namespaceURI, localName ); | StaticTag tag = new StaticTag( namespaceURI, localName, qName ); | protected TagScript createStaticTag( String namespaceURI, String localName, Attributes list ) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName ); DynaTagScript script = new DynaTagScript( tag ); // now iterate through through the expressions int size = list.getLength(); for ( int i = 0; i < size; i++ ) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = getExpressionFactory().createExpression( attributeValue ); if ( expression == null ) { expression = createConstantExpression( localName, attributeName, attributeValue ); } script.addAttribute( attributeName, expression ); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e ); throw createSAXException(e); } } |
tagScript = createStaticTag( namespaceURI, localName, list ); | tagScript = createStaticTag( namespaceURI, localName, qName, list ); | public void startElement( String namespaceURI, String localName, String qName, Attributes list ) throws SAXException { // if this is a tag then create a script to run it // otherwise pass the text to the current body tagScript = createTag( namespaceURI, localName, list ); if ( tagScript == null ) { tagScript = createStaticTag( namespaceURI, localName, list ); } tagScriptStack.add( tagScript ); if ( tagScript != null ) { // set parent relationship... Tag tag = tagScript.getTag(); tag.setParent( parentTag ); parentTag = tag; if ( textBuffer.length() > 0 ) { script.addScript( new TextScript( textBuffer.toString() ) ); textBuffer.setLength(0); } script.addScript( tagScript ); // start a new body scriptStack.push( script ); script = new ScriptBlock(); tag.setBody( script ); } else { // XXXX: might wanna handle empty elements later... textBuffer.append( "<" ); textBuffer.append( qName ); int size = list.getLength(); for ( int i = 0; i < size; i++ ) { textBuffer.append( " " ); textBuffer.append( list.getQName(i) ); textBuffer.append( "=" ); textBuffer.append( "\"" ); textBuffer.append( list.getValue(i) ); textBuffer.append( "\"" ); } textBuffer.append( ">" ); } } |
Tag tag = null; | Tag tag; | public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(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(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } } |
Object value = null; | Object value; | public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(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(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } } |
if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) | if( expat.prefix != null && expat.prefix.length() > 0 && tag instanceof StaticTag ) { | public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(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(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } } |
} | public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(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(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } } |
|
assertFalse("year isNullable incorrect", yearCol.isNullable()); | assertFalse("year isDefinitelyNullable incorrect", yearCol.isDefinitelyNullable()); | public void testPopulateTable() throws ArchitectException { assertFalse("Table should not have been populated already", table.isPopulated()); table.populate(); assertTrue("Table should been populated", table.isPopulated()); // spot-check that expected columns exist SQLColumn yearCol, teamCol, strikeoutsCol; assertNotNull("year column not found", yearCol = table.getColumnByName("year")); assertNotNull("team column not found", teamCol = table.getColumnByName("team")); assertNotNull("league column not found", table.getColumnByName("league")); assertNotNull("strikeouts column not found", strikeoutsCol = table.getColumnByName("strikeouts")); // check that all columns are owned by the correct table assertEquals("column doesn't belong to correct parent!", table, yearCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, teamCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, strikeoutsCol.getParent()); // check for PK vs non PK attributes assertTrue("year should have been flagged as PK", yearCol.isPrimaryKey()); assertEquals("year nullability incorrect", yearCol.getNullable(), DatabaseMetaData.columnNoNulls); assertFalse("year isNullable incorrect", yearCol.isNullable()); assertFalse("strikeouts should have been flagged as PK", strikeoutsCol.isPrimaryKey()); assertEquals("strikeouts nullability incorrect", strikeoutsCol.getNullable(), DatabaseMetaData.columnNullable); assertTrue("strikeouts isNullable incorrect", strikeoutsCol.isNullable()); // check column name comparator Comparator nameComp = new SQLColumn.ColumnNameComparator(); assertTrue(nameComp.compare(yearCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(teamCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(strikeoutsCol, yearCol) < 0); assertTrue(nameComp.compare(strikeoutsCol, teamCol) < 0); assertTrue(nameComp.compare(yearCol, yearCol) == 0); teamCol.setColumnName("year"); assertTrue(nameComp.compare(yearCol, teamCol) == 0); } |
assertTrue("strikeouts isNullable incorrect", strikeoutsCol.isNullable()); | assertTrue("strikeouts isDefinitelyNullable incorrect", strikeoutsCol.isDefinitelyNullable()); | public void testPopulateTable() throws ArchitectException { assertFalse("Table should not have been populated already", table.isPopulated()); table.populate(); assertTrue("Table should been populated", table.isPopulated()); // spot-check that expected columns exist SQLColumn yearCol, teamCol, strikeoutsCol; assertNotNull("year column not found", yearCol = table.getColumnByName("year")); assertNotNull("team column not found", teamCol = table.getColumnByName("team")); assertNotNull("league column not found", table.getColumnByName("league")); assertNotNull("strikeouts column not found", strikeoutsCol = table.getColumnByName("strikeouts")); // check that all columns are owned by the correct table assertEquals("column doesn't belong to correct parent!", table, yearCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, teamCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, strikeoutsCol.getParent()); // check for PK vs non PK attributes assertTrue("year should have been flagged as PK", yearCol.isPrimaryKey()); assertEquals("year nullability incorrect", yearCol.getNullable(), DatabaseMetaData.columnNoNulls); assertFalse("year isNullable incorrect", yearCol.isNullable()); assertFalse("strikeouts should have been flagged as PK", strikeoutsCol.isPrimaryKey()); assertEquals("strikeouts nullability incorrect", strikeoutsCol.getNullable(), DatabaseMetaData.columnNullable); assertTrue("strikeouts isNullable incorrect", strikeoutsCol.isNullable()); // check column name comparator Comparator nameComp = new SQLColumn.ColumnNameComparator(); assertTrue(nameComp.compare(yearCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(teamCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(strikeoutsCol, yearCol) < 0); assertTrue(nameComp.compare(strikeoutsCol, teamCol) < 0); assertTrue(nameComp.compare(yearCol, yearCol) == 0); teamCol.setColumnName("year"); assertTrue(nameComp.compare(yearCol, teamCol) == 0); } |
addComponentListener(new ResizeListener()); | public HaploView(){ //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); /* 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(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); 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]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); clearBlocksItem = new JMenuItem(CLEAR_BLOCKS); setAccelerator(clearBlocksItem, 'C', false); clearBlocksItem.addActionListener(this); clearBlocksItem.setEnabled(false); analysisMenu.add(clearBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
|
public String getRole() { | public String[] getRole() { | public String getRole() { return role; } |
public void setRole(String role) { | public void setRole(String[] role) { | public void setRole(String role) { this.role = role; } |
Object value = expression.evaluate(context); | Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } | public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag); } catch (JellyException e) { throw new JellyTagException(e); } 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 (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } } |
andMask &= StorableGenerator.PROPERTY_STATE_MASK << ((ordinal & 0xf) * 2); | andMask &= ~(StorableGenerator.PROPERTY_STATE_MASK << ((ordinal & 0xf) * 2)); | generateAbstractClass(Class<S> storableClass, boolean isMaster) throws SupportException { EnumSet<MasterFeature> features; if (isMaster) { features = EnumSet.of(MasterFeature.VERSIONING, MasterFeature.UPDATE_FULL, MasterFeature.INSERT_SEQUENCES, MasterFeature.INSERT_CHECK_REQUIRED); } else { features = EnumSet.of(MasterFeature.UPDATE_FULL); } final Class<? extends S> abstractClass = MasterStorableGenerator.getAbstractClass(storableClass, features); ClassInjector ci = ClassInjector.create (storableClass.getName(), abstractClass.getClassLoader()); ClassFile cf = new ClassFile(ci.getClassName(), abstractClass); cf.setModifiers(cf.getModifiers().toAbstract(true)); cf.markSynthetic(); cf.setSourceFile(RawStorableGenerator.class.getName()); cf.setTarget("1.5"); // Declare some types. final TypeDesc storableType = TypeDesc.forClass(Storable.class); final TypeDesc triggerSupportType = TypeDesc.forClass(TriggerSupport.class); final TypeDesc masterSupportType = TypeDesc.forClass(MasterSupport.class); final TypeDesc rawSupportType = TypeDesc.forClass(RawSupport.class); final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class); // Add constructors. // 1: Accepts a RawSupport. // 2: Accepts a RawSupport and an encoded key. // 3: Accepts a RawSupport, an encoded key and an encoded data. for (int i=1; i<=3; i++) { TypeDesc[] params = new TypeDesc[i]; params[0] = rawSupportType; if (i >= 2) { params[1] = byteArrayType; if (i == 3) { params[2] = byteArrayType; } } MethodInfo mi = cf.addConstructor(Modifiers.PUBLIC, params); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.loadLocal(b.getParameter(0)); b.invokeSuperConstructor(new TypeDesc[] {masterSupportType}); if (i >= 2) { params = new TypeDesc[] {byteArrayType}; b.loadThis(); b.loadLocal(b.getParameter(1)); b.invokeVirtual(DECODE_KEY_METHOD_NAME, null, params); if (i == 3) { b.loadThis(); b.loadLocal(b.getParameter(2)); b.invokeVirtual(DECODE_DATA_METHOD_NAME, null, params); // Indicate that object is clean by calling markAllPropertiesClean. b.loadThis(); b.invokeVirtual(MARK_ALL_PROPERTIES_CLEAN, null, null); } else { // Only the primary key is clean. Calling // markPropertiesClean might have no effect since subclass // may set fields directly. Instead, set state bits directly. Collection<? extends StorableProperty<S>> properties = StorableIntrospector .examine(storableClass).getPrimaryKeyProperties().values(); final int count = properties.size(); int ordinal = 0; int andMask = ~0; int orMask = 0; for (StorableProperty property : properties) { orMask |= StorableGenerator.PROPERTY_STATE_CLEAN << ((ordinal & 0xf) * 2); andMask &= StorableGenerator.PROPERTY_STATE_MASK << ((ordinal & 0xf) * 2); ordinal++; if ((ordinal & 0xf) == 0 || ordinal >= count) { String stateFieldName = StorableGenerator.PROPERTY_STATE_FIELD_NAME + ((ordinal - 1) >> 4); b.loadThis(); if (andMask == 0) { b.loadConstant(orMask); } else { b.loadThis(); b.loadField(stateFieldName, TypeDesc.INT); b.loadConstant(andMask); b.math(Opcode.IAND); b.loadConstant(orMask); b.math(Opcode.IOR); } b.storeField(stateFieldName, TypeDesc.INT); andMask = ~0; orMask = 0; } } } } b.returnVoid(); } // Declare protected abstract methods. { cf.addMethod(Modifiers.PROTECTED.toAbstract(true), ENCODE_KEY_METHOD_NAME, byteArrayType, null); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), DECODE_KEY_METHOD_NAME, null, new TypeDesc[]{byteArrayType}); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), ENCODE_DATA_METHOD_NAME, byteArrayType, null); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), DECODE_DATA_METHOD_NAME, null, new TypeDesc[]{byteArrayType}); } // Add required protected doTryLoad_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_LOAD_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(FetchException.class)); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {byteArrayType}; b.invokeInterface(rawSupportType, "tryLoad", byteArrayType, params); LocalVariable encodedDataVar = b.createLocalVariable(null, byteArrayType); b.storeLocal(encodedDataVar); b.loadLocal(encodedDataVar); Label notNull = b.createLabel(); b.ifNullBranch(notNull, false); b.loadConstant(false); b.returnValue(TypeDesc.BOOLEAN); notNull.setLocation(); b.loadThis(); b.loadLocal(encodedDataVar); params = new TypeDesc[] {byteArrayType}; b.invokeVirtual(DECODE_DATA_METHOD_NAME, null, params); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryInsert_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_INSERT_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // return rawSupport.tryInsert(this, this.encodeKey$(), this.encodeData$()); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); // pass this to tryInsert method b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); b.loadThis(); b.invokeVirtual(ENCODE_DATA_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {storableType, byteArrayType, byteArrayType}; b.invokeInterface(rawSupportType, "tryInsert", TypeDesc.BOOLEAN, params); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryUpdate_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_UPDATE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // rawSupport.store(this, this.encodeKey$(), this.encodeData$()); // return true; b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); // pass this to store method b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); b.loadThis(); b.invokeVirtual(ENCODE_DATA_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {storableType, byteArrayType, byteArrayType}; b.invokeInterface(rawSupportType, "store", null, params); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryDelete_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_DELETE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // return rawSupport.tryDelete(this.encodeKey$()); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {byteArrayType}; b.invokeInterface(rawSupportType, "tryDelete", TypeDesc.BOOLEAN, params); b.returnValue(TypeDesc.BOOLEAN); } return ci.defineClass(cf); } |
if (dPrimeTable.length == 0){ printDetails = false; } | public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //TODO: finish implementing scaling gizmo /*//deal with adding some space to better display data with large gaps int cumulativeGap[] = new int[Chromosome.getFilteredSize()]; for (int i = 0; i < cumulativeGap.length; i++){ cumulativeGap[i] = 0; } if (theData.infoKnown){ double mean = (((SNP)Chromosome.markers[Chromosome.markers.length-1]).getPosition() - ((SNP)Chromosome.markers[0]).getPosition())/Chromosome.markers.length-1; for (int i = 1; i < cumulativeGap.length; i++){ double sep = Chromosome.getMarker(i).getPosition() - Chromosome.getMarker(i-1).getPosition(); if (sep > mean*10){ cumulativeGap[i] = cumulativeGap[i-1] + (int)(sep/mean)*4; }else{ cumulativeGap[i] = cumulativeGap[i-1]; } } } */ //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = (visRect.x-clickXShift-(visRect.y + visRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((visRect.x + visRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((visRect.x-clickXShift)+(visRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } int lineSpan = (dPrimeTable.length-1) * boxSize; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fillRect(left, top, lineSpan, TRACK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left, top, lineSpan, TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left+1, top+1, lineSpan-1, TICK_HEIGHT-1); g2.setColor(Color.black); g2.drawRect(left, top, lineSpan, TICK_HEIGHT); for (int i = 0; i < Chromosome.getFilteredSize(); i++){ double pos = (Chromosome.getFilteredMarker(i).getPosition() - minpos) / spanpos; int xx = (int) (left + lineSpan*pos); g2.setStroke(thickerStroke); g2.drawLine(xx, top, xx, top + TICK_HEIGHT); g2.setStroke(thinnerStroke); g2.drawLine(xx, top + TICK_HEIGHT, left + i*boxSize, top+TICK_BOTTOM); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printDetails){ widestMarkerName = metrics.stringWidth(Chromosome.getFilteredMarker(0).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(Chromosome.getFilteredMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } g2.drawString(Chromosome.getFilteredMarker(x).getName(),TEXT_GAP, x*boxSize + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printDetails){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable[x][y] == null){ continue; } double d = dPrimeTable[x][y].getDPrime(); //double l = dPrimeTable[x][y].getLOD(); Color boxColor = dPrimeTable[x][y].getColor(); // draw markers above int xx = left + (x + y) * boxSize / 2; int yy = top + (y - x) * boxSize / 2; diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDetails){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } boolean even = true; //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.drawLine(left + (2*first) * boxSize/2 - boxRadius, top, left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius); g2.drawLine(left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius, left + (2*last) * boxSize/2+boxRadius, top); for (int j = first; j <= last; j++){ if (theData.isInBlock[j]){ g2.setStroke(fatStroke); }else{ g2.setStroke(dashedFatStroke); } g2.drawLine(left+j*boxSize-boxSize/2, top-blockDispHeight, left+j*boxSize+boxSize/2, top-blockDispHeight); } //lines to connect to block display g2.setStroke(fatStroke); g2.drawLine(left + first*boxSize-boxSize/2, top-1, left+first*boxSize-boxSize/2, top-blockDispHeight); g2.drawLine(left+last*boxSize+boxSize/2, top-1, left+last*boxSize+boxSize/2, top-blockDispHeight); if (printDetails){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getFilteredMarker(last).getPosition() - Chromosome.getFilteredMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, left+first*boxSize-boxSize/2+TEXT_GAP, top-boxSize/3); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getWidth() < visRect.width){ //dumb bug where little datasets popup the box in the wrong place smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.length; x++){ g.drawString(displayStrings[x],popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2+WM_BD_TOTAL, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < dPrimeTable.length-1; x++){ for (int y = x+1; y < dPrimeTable.length; y++){ if (dPrimeTable[x][y] == null){ continue; } double xx = (x + y)*prefBoxSize/2+wmBorder.getBorderInsets(this).left; double yy = (y - x)*prefBoxSize/2+wmBorder.getBorderInsets(this).top + WM_BD_TOTAL; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable[x][y].getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left+(int)(prefBoxSize*first), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)((last-first+1)*prefBoxSize), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } } |
|
char markerChars[] = nfMarker.format(markerNums[z]+1).toCharArray(); | char markerChars[] = nfMarker.format(Chromosome.realIndex[markerNums[z]]+1).toCharArray(); | public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(); int markerCount = Chromosome.getSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH + -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(markerNums[z]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines int crossValue = (int) (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); for (int m = 0; m < 3; m++) { // 7*CHAR_WIDTH/2 = CHAR_WIDTH*3.5 to center it better // since the . char is right-aligned, and visually off g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } //int multiX = x + totalWidth + 3; //g.drawString(nfMulti.format(multidprimeArray[i]), // multiX+2, windowY - 3); } left += LINE_SPAN; //x += (totalWidth + 40); //y = verticalOffset; //left = textRight + LINE_SPAN; } } |
OrderingList<S> unused = score.getUnusedOrdering(); if (unused.size() > 0) { for (OrderedProperty<S> prop : unused) { ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } | private Result buildResult(Filter<S> filter, OrderingList<S> ordering) throws SupportException, RepositoryException { List<IndexedQueryAnalyzer<S>.Result> subResults; if (filter == null) { subResults = Collections.singletonList(mIndexAnalyzer.analyze(filter, ordering)); } else { subResults = splitIntoSubResults(filter, ordering); } if (subResults.size() <= 1) { // Total ordering not required. return new Result(subResults); } // If any orderings have an unspecified direction, switch to ASCENDING // or DESCENDING, depending on which is more popular. Then build new // sub-results. for (int pos = 0; pos < ordering.size(); pos++) { OrderedProperty<S> op = ordering.get(pos); if (op.getDirection() != Direction.UNSPECIFIED) { continue; } // Find out which direction is most popular for this property. Tally tally = new Tally(op.getChainedProperty()); for (IndexedQueryAnalyzer<S>.Result result : subResults) { tally.increment(findHandledDirection(result, op)); } ordering = ordering.replace(pos, op.direction(tally.getBestDirection())); // Re-calc with specified direction. Only do one property at a time // since one simple change might alter the query plan. subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. return new Result(subResults); } } // Gather all the keys available. As ordering properties touch key // properties, they are removed from all key sets. When a key set size // reaches zero, total ordering has been achieved. List<Set<ChainedProperty<S>>> keys = getKeys(); // Check if current ordering is total. for (OrderedProperty<S> op : ordering) { ChainedProperty<S> property = op.getChainedProperty(); if (pruneKeys(keys, property)) { // Found a key which is fully covered, indicating total ordering. return new Result(subResults, ordering); } } // Create a super key which contains all the properties required for // total ordering. The goal here is to append these properties to the // ordering in a fashion that takes advantage of each index's natural // ordering. This in turn should cause any sort operation to operate // over smaller groups. Smaller groups means smaller sort buffers. // Smaller sort buffers makes a merge sort happy. // Super key could be stored simply in a set, but a map makes it // convenient for tracking tallies. Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>(); for (Set<ChainedProperty<S>> key : keys) { for (ChainedProperty<S> property : key) { superKey.put(property, new Tally(property)); } } // Keep looping until total ordering achieved. while (true) { // For each ordering score, find the next free property. If // property is in the super key increment a tally associated with // property direction. Choose the property with the best tally and // augment the orderings with it and create new sub-results. // Remove the property from the super key and the key set. If any // key is now fully covered, a total ordering has been achieved. for (IndexedQueryAnalyzer<S>.Result result : subResults) { OrderingScore<S> score = result.getCompositeScore().getOrderingScore(); OrderingList<S> free = score.getFreeOrdering(); if (free.size() > 0) { OrderedProperty<S> prop = free.get(0); ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } Tally best = bestTally(superKey.values()); ChainedProperty<S> bestProperty = best.getProperty(); // Now augment the orderings and create new sub-results. ordering = ordering.concat(OrderedProperty.get(bestProperty, best.getBestDirection())); subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. break; } // Remove property from super key and key set... superKey.remove(bestProperty); if (superKey.size() == 0) { break; } if (pruneKeys(keys, bestProperty)) { break; } // Clear the tallies for the next run. for (Tally tally : superKey.values()) { tally.clear(); } } return new Result(subResults, ordering); } |
|
private List<Set<ChainedProperty<S>>> getKeys() { | private List<Set<ChainedProperty<S>>> getKeys() throws SupportException, RepositoryException { | private List<Set<ChainedProperty<S>>> getKeys() { StorableInfo<S> info = StorableIntrospector.examine(mIndexAnalyzer.getStorableType()); List<Set<ChainedProperty<S>>> keys = new ArrayList<Set<ChainedProperty<S>>>(); keys.add(stripOrdering(info.getPrimaryKey().getProperties())); for (StorableKey<S> altKey : info.getAlternateKeys()) { keys.add(stripOrdering(altKey.getProperties())); } return keys; } |
Collection<StorableIndex<S>> indexes = mRepoAccess.storageAccessFor(getStorableType()).getAllIndexes(); for (StorableIndex<S> index : indexes) { if (!index.isUnique()) { continue; } int propCount = index.getPropertyCount(); Set<ChainedProperty<S>> props = new HashSet<ChainedProperty<S>>(propCount); for (int i=0; i<propCount; i++) { props.add(index.getOrderedProperty(i).getChainedProperty()); } keys.add(props); } | private List<Set<ChainedProperty<S>>> getKeys() { StorableInfo<S> info = StorableIntrospector.examine(mIndexAnalyzer.getStorableType()); List<Set<ChainedProperty<S>>> keys = new ArrayList<Set<ChainedProperty<S>>>(); keys.add(stripOrdering(info.getPrimaryKey().getProperties())); for (StorableKey<S> altKey : info.getAlternateKeys()) { keys.add(stripOrdering(altKey.getProperties())); } return keys; } |
|
} if (!result.getCompositeScore().getFilteringScore().hasAnyMatches()) { if (full == null) { full = result; } | splitIntoSubResults(Filter<S> filter, OrderingList<S> ordering) throws SupportException, RepositoryException { // Required for split to work. Filter<S> dnfFilter = filter.disjunctiveNormalForm(); Splitter splitter = new Splitter(ordering); RepositoryException e = dnfFilter.accept(splitter, null); if (e != null) { throw e; } List<IndexedQueryAnalyzer<S>.Result> subResults = splitter.mSubResults; // Check if any sub-result handles nothing. If so, a full scan is the // best option for the entire query and all sub-results merge into a // single sub-result. Any sub-results which filter anything and contain // a join property in the filter are exempt from the merge. This is // because fewer joins are read than if a full scan is performed for // the entire query. The resulting union has both a full scan and an // index scan. IndexedQueryAnalyzer<S>.Result full = null; for (IndexedQueryAnalyzer<S>.Result result : subResults) { if (!result.handlesAnything()) { full = result; break; } } if (full == null) { // Okay, no full scan needed. return subResults; } List<IndexedQueryAnalyzer<S>.Result> mergedResults = new ArrayList<IndexedQueryAnalyzer<S>.Result>(); for (IndexedQueryAnalyzer<S>.Result result : subResults) { if (result == full) { // Add after everything has been merged into it. continue; } boolean exempt = result.getCompositeScore().getFilteringScore().hasAnyMatches(); if (exempt) { // Must also have a join in the filter to be exempt. List<PropertyFilter<S>> subFilters = PropertyFilterList.get(result.getFilter()); joinCheck: { for (PropertyFilter<S> subFilter : subFilters) { if (subFilter.getChainedProperty().getChainCount() > 0) { // A chain implies a join was followed, so result is exempt. break joinCheck; } } // No joins found, result is not exempt from merging into full scan. exempt = false; } } if (exempt) { mergedResults.add(result); } else { full = full.mergeRemainderFilter(result.getFilter()); } } if (mergedResults.size() == 0) { // Nothing was exempt. Rather than return a result with a dnf // filter, return full scan with a simpler reduced filter. full.setRemainderFilter(filter.reduce()); } mergedResults.add(full); return mergedResults; } |
|
ctrl.setView( this ); | public PhotoInfoEditor( PhotoInfoController ctrl ) { super(); createUI(); this.ctrl = ctrl; } |
|
System.err.println( "exception while saving" + e.getMessage() ); | public void actionPerformed( ActionEvent evt ) { if ( evt.getActionCommand().equals( "save" ) ) { System.out.println( "Saving data" ); try { ctrl.save(); } catch ( Exception e ) { } } else if ( evt.getActionCommand().equals( "discard" ) ) { System.out.println( "Discarding data" ); ctrl.discard(); } } |
|
shootingDayDoc = shootingDayField.getDocument(); shootingDayDoc.addDocumentListener( this ); | protected void createUI() { // Create the fields & their labels // Photographer field JLabel photographerLabel = new JLabel( "Photographer" ); photographerField = new JTextField( 30 ); photographerDoc = photographerField.getDocument(); photographerDoc.addDocumentListener( this ); // 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( )); // Shooting place field JLabel shootingPlaceLabel = new JLabel( "Shooting place" ); shootingPlaceField = new JTextField( 30 ); shootingPlaceDoc = shootingPlaceField.getDocument(); shootingPlaceDoc.addDocumentListener( this ); // Descrription 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 ); // 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(); setLayout( layout ); JLabel[] labels = { photographerLabel, shootingDayLabel, shootingPlaceLabel }; JTextField[] fields = { photographerField, shootingDayField, shootingPlaceField }; addLabelTextRows( labels, fields, layout, this ); 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; add( saveBtn ); layout.setConstraints( saveBtn, c ); c.gridy = GridBagConstraints.RELATIVE; add( discardBtn ); layout.setConstraints( discardBtn, c ); } |
|
ctrl.setField( changedField, newValue ); | ctrl.viewChanged( this, changedField, newValue ); | public void insertUpdate( DocumentEvent ev ) { Document changedDoc = ev.getDocument(); String changedField = null; Object newValue = null; if ( changedDoc == photographerDoc ) { changedField = PhotoInfoController.PHOTOGRAPHER; newValue = photographerField.getText(); System.err.println( "New photographer: " + newValue ); } else if ( changedDoc == shootingDayDoc ) { changedField = PhotoInfoController.SHOOTING_DATE; newValue = shootingDayField.getValue(); } else if ( changedDoc == shootingPlaceDoc ) { changedField = PhotoInfoController.SHOOTING_PLACE; newValue = shootingPlaceField.getText(); } else { System.err.println( "insertUpdate from unknown event!!!" ); } ctrl.setField( changedField, newValue ); } |
finally { if ( ! context.isCacheTags() ) { clearTag(); } } | public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag); } catch (JellyException e) { throw new JellyTagException(e); } 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 = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } } |
|
dPrimeDisplay.colorDPrime(currentScheme); | public void stateChanged(ChangeEvent e) { int tabNum = tabs.getSelectedIndex(); if (tabNum == VIEW_D_NUM || tabNum == VIEW_HAP_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(true); }else if (tabNum == VIEW_TDT_NUM || tabNum == VIEW_CHECK_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(false); }else{ exportMenuItems[0].setEnabled(false); exportMenuItems[1].setEnabled(false); } if (tabNum == VIEW_D_NUM){ keyMenu.setEnabled(true); }else{ keyMenu.setEnabled(false); } viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,CheckDataPanel.STATUS_COL)).booleanValue(); } int count = 0; for (int i = 0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ count++; } } Chromosome.realIndex = new int[count]; int k = 0; for (int i =0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ Chromosome.realIndex[k] = i; k++; } } theData.filteredDPrimeTable = theData.getFilteredTable(); //after editing the filtered marker list, needs to be prodded into //resizing correctly Dimension size = dPrimeDisplay.getSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } hapDisplay.theData = theData; changeBlocks(currentBlockDef); if (tdtPanel != null){ tdtPanel.refreshTable(); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } if (hapDisplay != null && theData.blocksChanged){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } hapScroller.setViewportView(hapDisplay); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); theData.blocksChanged = false; } } |
|
out.println(CSVExport.toString(Arrays.asList(ProfileColumn.values()))); | ProfileColumn[] columns = ProfileColumn.values(); out.println(CSVExport.toString(Arrays.asList(columns))); | public void format(OutputStream nout, List<ProfileResult> profileResult, ProfileManager pm) throws Exception { PrintWriter out = new PrintWriter(nout); // Print a header out.println(CSVExport.toString(Arrays.asList(ProfileColumn.values()))); DateFormat dateFormat = (DateFormat) new DateRendererFactory().getFormat(); DecimalFormat decFormat = (DecimalFormat) new DecimalRendererFactory().getFormat(); // Now print column profile for ( ProfileResult result : profileResult ) { if ( !(result instanceof ColumnProfileResult) ) continue; SQLColumn c = (SQLColumn) result.getProfiledObject(); SQLTable t = c.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(t); List<Object> commonData = new ArrayList<Object>(); commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); out.println(CSVExport.toString(commonData)); } out.close(); } |
DecimalFormat pctFormat = (DecimalFormat) new PercentRendererFactory().getFormat(); | public void format(OutputStream nout, List<ProfileResult> profileResult, ProfileManager pm) throws Exception { PrintWriter out = new PrintWriter(nout); // Print a header out.println(CSVExport.toString(Arrays.asList(ProfileColumn.values()))); DateFormat dateFormat = (DateFormat) new DateRendererFactory().getFormat(); DecimalFormat decFormat = (DecimalFormat) new DecimalRendererFactory().getFormat(); // Now print column profile for ( ProfileResult result : profileResult ) { if ( !(result instanceof ColumnProfileResult) ) continue; SQLColumn c = (SQLColumn) result.getProfiledObject(); SQLTable t = c.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(t); List<Object> commonData = new ArrayList<Object>(); commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); out.println(CSVExport.toString(commonData)); } out.close(); } |
|
commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); | for ( ProfileColumn pc : columns ) { switch(pc) { case DATABASE: commonData.add(t.getParentDatabase().getName()); break; case CATALOG: commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); break; case SCHEMA: commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); break; case TABLE: commonData.add(t.getName()); break; case COLUMN: commonData.add(c.getName()); break; case RUNDATE: Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); break; case RECORD_COUNT: commonData.add(tpr.getRowCount()); break; case DATA_TYPE: commonData.add(c.getType()); break; case NULL_COUNT: commonData.add(((ColumnProfileResult) result).getNullCount()); break; case PERCENT_NULL: if ( tpr.getRowCount() == 0 ) commonData.add("n/a"); else commonData.add( pctFormat.format( ((ColumnProfileResult) result).getNullCount() / (double)tpr.getRowCount())); break; case UNIQUE_COUNT: commonData.add(((ColumnProfileResult) result).getDistinctValueCount()); break; case PERCENT_UNIQUE: if ( tpr.getRowCount() == 0 ) commonData.add("n/a"); else commonData.add( pctFormat.format( ((ColumnProfileResult) result).getDistinctValueCount() / (double)tpr.getRowCount())); break; case MIN_LENGTH: commonData.add(((ColumnProfileResult) result).getMinLength()); break; case MAX_LENGTH: commonData.add(((ColumnProfileResult) result).getMaxLength()); break; case AVERAGE_LENGTH: commonData.add(decFormat.format(((ColumnProfileResult) result).getAvgLength())); break; case MIN_VALUE: commonData.add(((ColumnProfileResult) result).getMinValue()); break; case MAX_VALUE: commonData.add(((ColumnProfileResult) result).getMaxValue()); break; case AVERAGE_VALUE: String formattedValue; Object value = ((ColumnProfileResult) result).getAvgValue(); if (value == null) { formattedValue = ""; } else if (value instanceof Number) { formattedValue = decFormat.format(value); } else { formattedValue = value.toString(); } commonData.add(formattedValue); break; case TOP_VALUE: commonData.add(""); break; default: throw new IllegalStateException("Need code to handle this column!"); } } | public void format(OutputStream nout, List<ProfileResult> profileResult, ProfileManager pm) throws Exception { PrintWriter out = new PrintWriter(nout); // Print a header out.println(CSVExport.toString(Arrays.asList(ProfileColumn.values()))); DateFormat dateFormat = (DateFormat) new DateRendererFactory().getFormat(); DecimalFormat decFormat = (DecimalFormat) new DecimalRendererFactory().getFormat(); // Now print column profile for ( ProfileResult result : profileResult ) { if ( !(result instanceof ColumnProfileResult) ) continue; SQLColumn c = (SQLColumn) result.getProfiledObject(); SQLTable t = c.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(t); List<Object> commonData = new ArrayList<Object>(); commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); out.println(CSVExport.toString(commonData)); } out.close(); } |
createDatabase(); | private JUnitOJBManager() { System.setProperty( "photovault.configfile", "conf/junittest_config.xml" ); log.error( "Initializing OB for JUnit tests" ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); settings.setConfiguration( "pv_junit" ); PVDatabase db = settings.getDatabase( "pv_junit" ); if ( db == null ) { log.error( "Could not find dbname for configuration " ); return; } if ( ODMG.initODMG( "", "", db ) ) { log.debug( "Connection succesful!!!" ); } else { log.error( "Error logging into Photovault" ); } if ( db.getSchemaVersion() < PVDatabase.CURRENT_SCHEMA_VERSION ) { SchemaUpdateAction updater = new SchemaUpdateAction( db ); updater.upgradeDatabase(); } } |
|
makeOrdering(StorableTestBasic.class, "stringProp"); | makeOrdering(StorableTestBasic.class, "-stringProp"); | public void testIdentityAndRangeMatch() throws Exception { // These tests are not as exhaustive, as I don't expect the combination // of identity and ranges to interfere with each other. StorableIndex<StorableTestBasic> index; Filter<StorableTestBasic> filter; FilterValues<StorableTestBasic> values; CompositeScore<StorableTestBasic> score; Mock<StorableTestBasic> executor; index = makeIndex(StorableTestBasic.class, "intProp", "-doubleProp", "stringProp"); filter = Filter.filterFor(StorableTestBasic.class, "intProp = ? & doubleProp > ? & doubleProp < ?"); values = filter.initialFilterValues(); filter = values.getFilter(); score = CompositeScore.evaluate(index, filter, null); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertFalse(executor.mReverseOrder); /////// score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "doubleProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertTrue(executor.mReverseOrder); /////// score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "stringProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertFalse(executor.mReverseOrder); /////// filter = Filter.filterFor(StorableTestBasic.class, "intProp = ? & doubleProp = ? & stringProp < ?"); values = filter.initialFilterValues(); filter = values.getFilter(); score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "-stringProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with("foo")); assertEquals(3, executor.mIdentityValues[0]); assertEquals(56.5, executor.mIdentityValues[1]); assertEquals(BoundaryType.OPEN, executor.mRangeStartBoundary); assertEquals(null, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals("foo", executor.mRangeEndValue); assertFalse(executor.mReverseRange); assertTrue(executor.mReverseOrder); assertEquals(values.getFilter(), executor.getFilter()); List<OrderedProperty<StorableTestBasic>> expectedOrdering = makeOrdering(StorableTestBasic.class, "stringProp"); assertEquals(expectedOrdering, executor.getOrdering()); } |
Connection con = null; | Connection con = null; Connection tCon = null; | public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } } |
Connection tCon = target.getConnection(); | tCon = target.getConnection(); | public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } } |
throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); | throw new ArchitectException("There is no entry for \"" + repositoryDataSource.get(ArchitectDataSource.PL_UID) + "\" in the PL_USER table"); | public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } } |
Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); | for (SQLColumn outputCol : outputTable.getColumns()) { | public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } } |
outputTableNum++; | public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } } |
|
logger.error("Couldn't close connection", e); | logger.error("Couldn't close repository connection", e); } try { if (tCon != null) tCon.close(); } catch (SQLException e) { logger.error("Couldn't close target connection", e); | public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } } |
sql.append(",").append(SQL.quote("Generated by POWER*Architect " + PL_GENERATOR_VERSION)); | sql.append(",").append(SQL.quote("Generated by Power*Architect " + PL_GENERATOR_VERSION)); | public void insertJobDetail(Connection con, int seqNo, String objectType, String objectName) throws SQLException { String status = "Unknown"; StringBuffer sql = new StringBuffer("INSERT INTO "); sql.append(DDLUtils.toQualifiedName(repositoryCatalog, repositorySchema, "JOB_DETAIL")); sql .append(" (JOB_ID, JOB_PROCESS_SEQ_NO, OBJECT_TYPE, OBJECT_NAME, JOB_DETAIL_COMMENT, LAST_update_DATE, LAST_update_USER, FAILURE_ABORT_IND, WARNING_ABORT_IND, PKG_PARAM, ACTIVE_IND, LAST_update_OS_USER )"); sql.append(" VALUES ("); sql.append(SQL.quote(jobId)); // JOB_ID sql.append(",").append(seqNo); // JOB_PROCESS_SEQ_NO sql.append(",").append(SQL.quote(objectType)); // OBJECT_TYPE sql.append(",").append(SQL.quote(objectName)); // OBJECT_NAME sql.append(",").append(SQL.quote("Generated by POWER*Architect " + PL_GENERATOR_VERSION)); // JOB_DETAIL_COMMENT sql.append(",").append(SQL.escapeDate(con, new java.util.Date())); // LAST_update_DATE sql.append(",").append(SQL.quote(con.getMetaData().getUserName())); // LAST_update_USER sql.append(",").append(SQL.quote("N")); // FAILURE_ABORT_IND sql.append(",").append(SQL.quote("N")); // WARNING_ABORT_IND sql.append(",").append(SQL.quote(null)); // PKG_PARAM sql.append(",").append(SQL.quote("Y")); // ACTIVE_IND sql.append(",").append(SQL.quote(System.getProperty("user.name"))); // LAST_update_OS_USER sql.append(")"); logWriter.info("INSERT into JOB DETAIL, PK=" + jobId + "|" + seqNo); Statement s = con.createStatement(); try { logger.debug("INSERT JOB DETAIL: " + sql.toString()); s.executeUpdate(sql.toString()); status = "OK"; } catch (SQLException e) { status = "Error"; throw e; } finally { if (s != null) { s.close(); } exportResultList.add(new LabelValueBean("Create Job Step " + seqNo + objectName, status)); } } |
String tagName, | TagScript tagScript, | public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws Exception { ExpressionFactory myFactory = getExpressionFactory(); if (myFactory == null) { myFactory = factory; } if (myFactory != null) { return CompositeExpression.parse(attributeValue, myFactory); } // will use a constant expression instead return new ConstantExpression(attributeValue); } |
db.addVolume( volume ); | try { db.addVolume( volume ); } catch (PhotovaultException ex) { ex.printStackTrace(); } | public void setUp() { String volumeRoot = "c:\\temp\\photoVaultVolumeTest"; volume = new Volume( "testVolume", volumeRoot ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); db = settings.getCurrentDatabase(); db.addVolume( volume ); } |
db.addVolume( extVolume ); | try { db.addVolume( extVolume ); } catch (PhotovaultException ex) { fail( ex.getMessage() ); } | public void testGetVolumeOfFile() { try { File testVolPath = File.createTempFile( "pv_voltest", "" ); VolumeBase extVolume = new ExternalVolume( "extvol", testVolPath.getAbsolutePath() ); db.addVolume( extVolume ); File test1 = new File( volume.getBaseDir(), "testfile" ); assertEquals( test1.getAbsolutePath() + " belongs to volume", volume, VolumeBase.getVolumeOfFile( test1 ) ); File test2 = new File( testVolPath, "testfile" ); assertEquals( test2.getAbsolutePath() + " belongs to volume", extVolume, VolumeBase.getVolumeOfFile( test2 ) ); File test3 = new File( testVolPath.getParentFile(), "testfile" ); this.assertNull( test3.getAbsoluteFile() + " does not belong to volume", VolumeBase.getVolumeOfFile( test3 ) ); // Test that null argument does not cause error VolumeBase.getVolumeOfFile( null ); } catch (IOException ex) { fail( "IOError: " + ex.getMessage() ); } } |
int response = chooser.showSaveDialog(parent); | File file = null; SaveableFileType type; while ( true ) { int response = chooser.showSaveDialog(parent); | public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); } |
if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); | if (response != JFileChooser.APPROVE_OPTION) { | public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); } |
switch(type) { | switch(type2) { | public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); } |
switch(type) { | switch(type2) { | public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } |
columns.setSelectedIndex(index); | protected void editColumn(int index) throws ArchitectException { if (index < 0) { return; } try { changingColumns = true; SQLColumn col = model.getColumn(index); if (col.getSourceColumn() == null) { sourceDB.setText("None Specified"); sourceTableCol.setText("None Specified"); } else { StringBuffer sourceDBSchema = new StringBuffer(); SQLObject so = col.getSourceColumn().getParentTable().getParent(); while (so != null) { sourceDBSchema.insert(0, so.getName()); sourceDBSchema.insert(0, "."); so = so.getParent(); } sourceDB.setText(sourceDBSchema.toString().substring(1)); sourceTableCol.setText(col.getSourceColumn().getParentTable().getName() +"."+col.getSourceColumn().getName()); } colName.setText(col.getName()); colType.setSelectedItem(SQLType.getType(col.getType())); colScale.setValue(new Integer(col.getScale())); colPrec.setValue(new Integer(col.getPrecision())); colNullable.setSelected(col.getNullable() == DatabaseMetaData.columnNullable); colRemarks.setText(col.getRemarks()); colDefaultValue.setText(col.getDefaultValue()); colInPK.setSelected(col.getPrimaryKeySeq() != null); } finally { changingColumns = false; } updateComponents(); colName.requestFocus(); } |
|
editColumn(0); | editColumn(columns.getSelectedIndex()); | public void intervalRemoved(ListDataEvent e) { try { if (model.getColumns().size() == 0) { Component c = getParent(); while ( ! (c instanceof Window)) { c = c.getParent(); } c.setVisible(false); } else { editColumn(0); } } catch (ArchitectException ex) { JOptionPane.showMessageDialog(this, "Can't edit the selected column"); logger.error("Can't edit the selected column", ex); } } |
if ((zoomLevel == 0) && (!lastSelection.equals("")) && (!forExport)) { g2.setFont(boxFont); int last_descent = g2.getFontMetrics().getDescent(); int last_box_x = (visRect.x + LAST_SELECTION_LEFT) - 2; int last_box_y = (visRect.y - g2.getFontMetrics().getHeight() + LAST_SELECTION_TOP + last_descent) - 1 ; int last_box_width = g2.getFontMetrics().stringWidth(lastSelection) + 4; int last_box_height = g2.getFontMetrics().getHeight() + 2; g2.setColor(Color.white); g2.fillRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.setColor(Color.black); g2.drawRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.drawString(lastSelection, LAST_SELECTION_LEFT + visRect.x, LAST_SELECTION_TOP + visRect.y); | if (lastSelection != null){ if ((zoomLevel == 0) && (!lastSelection.equals("")) && (!forExport)) { g2.setFont(boxFont); int last_descent = g2.getFontMetrics().getDescent(); int last_box_x = (visRect.x + LAST_SELECTION_LEFT) - 2; int last_box_y = (visRect.y - g2.getFontMetrics().getHeight() + LAST_SELECTION_TOP + last_descent) - 1 ; int last_box_width = g2.getFontMetrics().stringWidth(lastSelection) + 4; int last_box_height = g2.getFontMetrics().getHeight() + 2; g2.setColor(Color.white); g2.fillRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.setColor(Color.black); g2.drawRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.drawString(lastSelection, LAST_SELECTION_LEFT + visRect.x, LAST_SELECTION_TOP + visRect.y); } | public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() < 2){ //if there zero or only one valid marker return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } boolean printValues = true; if (zoomLevel != 0 || Options.getPrintWhat() == LD_NONE){ printValues = false; } printWhat = Options.getPrintWhat(); Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage,H_BORDER-GBROWSE_MARGIN,V_BORDER,this); imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop+1; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked JFreeChart jfc = ChartFactory.createXYLineChart(null,null,null, theData.analysisTracks, PlotOrientation.VERTICAL,false,false,false); //customise the analysis track XYPlot xyp = (XYPlot)jfc.getPlot(); //no x axis, since it takes up too much space. xyp.getDomainAxis().setAxisLineVisible(false); xyp.getDomainAxis().setTickLabelsVisible(false); xyp.getDomainAxis().setTickMarksVisible(false); //x range must align with markers xyp.getDomainAxis().setRange(minpos,maxpos); //size of the axis and graph inset double axisWidth = xyp.getRangeAxis(). reserveSpace(g2,xyp,new Rectangle(0,TRACK_HEIGHT),RectangleEdge.LEFT,null).getLeft(); RectangleInsets insets = xyp.getInsets(); jfc.setBackgroundPaint(BG_GREY); BufferedImage bi = jfc.createBufferedImage( (int)(lineSpan + axisWidth + insets.getLeft() + insets.getRight()),TRACK_HEIGHT); //hide the axis in the margin so everything lines up. g2.drawImage(bi,(int)(left - axisWidth - insets.getLeft()),top,this); top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getDisplayName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getDisplayName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); boolean foundSNP = false; for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); if (Chromosome.getMarker(x).getDisplayName().equals(theHV.getChosenMarker())){ g2.setColor(Color.blue); foundSNP = true; } g2.drawString(Chromosome.getMarker(x).getDisplayName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); if (foundSNP){ g2.setColor(Color.BLACK); foundSNP = false; } } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); double r = dPrimeTable.getLDStats(x,y).getRSquared(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val; if (printWhat == D_PRIME){ val = (int) (d * 100); }else if (printWhat == R_SQ){ val = (int) (r * 100); }else{ val = 100; } g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor.getGreen() < 100 && boxColor.getBlue() < 100 && boxColor.getRed() < 100){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); if (showWM && !forExport){ //dataset is big enough to require worldmap if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth))); //stick WM_BD in the middle of the blank space at the top of the worldmap final int WM_BD_GAP = (int)(infoHeight/(scalefactor*2)); final int WM_BD_HEIGHT = 2; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x] + infoHeight*2)/(scalefactor*2)) + wmBorder.getBorderInsets(this).top; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if the user has right-clicked to popup some marker info if(popupDrawRect != null){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); g.setFont(popupFont); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } // draw the cached last right-click selection // The purpose of testing for empty string is just to avoid an 2-unit empty white box if ((zoomLevel == 0) && (!lastSelection.equals("")) && (!forExport)) { g2.setFont(boxFont); // a bit extra on all side int last_descent = g2.getFontMetrics().getDescent(); int last_box_x = (visRect.x + LAST_SELECTION_LEFT) - 2; int last_box_y = (visRect.y - g2.getFontMetrics().getHeight() + LAST_SELECTION_TOP + last_descent) - 1 ; int last_box_width = g2.getFontMetrics().stringWidth(lastSelection) + 4; int last_box_height = g2.getFontMetrics().getHeight() + 2; g2.setColor(Color.white); g2.fillRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.setColor(Color.black); g2.drawRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.drawString(lastSelection, LAST_SELECTION_LEFT + visRect.x, LAST_SELECTION_TOP + visRect.y); } //see if we're drawing a worldmap resize rect if (resizeWMRect != null){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRect != null){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } } |
if (whichMarker >= theTable.length-1) return 0; | public int getLength(int x){ //same as above but for the filtered dataset int whichMarker = Chromosome.realIndex[x]; for (int m = theTable[whichMarker].length+whichMarker; m > whichMarker; m--){ if (Chromosome.filterIndex[m] != -1){ //length of array is one greater than difference of first and last elements return Chromosome.filterIndex[m] - Chromosome.filterIndex[whichMarker] + 1; } } return 0; } |
|
fieldCtrl.setValue( view1, "View2" ); | fieldCtrl.viewChanged( view1, "View2" ); | public void testFieldModification() { view1.setField( "View1" ); // Generate a bbogus event to demonstrate that this should propagate to view2 but not to view1 fieldCtrl.setValue( view1, "View2" ); assertEquals( "View2 not changed by updating view1", "View2", view2.getField() ); assertEquals( "View1 should not be changed", "View1", view1.getField() ); } |
output.append("<div id=\"" + getId() + "\">"); | if(!context.isRefreshRequest()){ output.append("<div id=\"" + getId() + "\">"); } | public final String draw(DashboardContext context) { String applicationId = context.getWebContext().getApplicationConfig().getApplicationId(); StringBuffer output = new StringBuffer(); if(event != null){ output.append("<script>"); output.append("addEventHandler(''" + event.source + "'', ''" + event.name + "'', ''" + getId() + "'', ''" + event.dataVariable + "'', ''" + applicationId + "'')"); output.append("</script>"); } // wrap wih div tag output.append("<div id=\"" + getId() + "\">"); try{ properties.context = context; if(!properties.hasUnresolvedVariable()) drawInternal(context, output); }finally{ properties.context = null; } output.append("</div>"); return output.toString(); } |
output.append("</div>"); | if(!context.isRefreshRequest()){ output.append("</div>"); } | public final String draw(DashboardContext context) { String applicationId = context.getWebContext().getApplicationConfig().getApplicationId(); StringBuffer output = new StringBuffer(); if(event != null){ output.append("<script>"); output.append("addEventHandler(''" + event.source + "'', ''" + event.name + "'', ''" + getId() + "'', ''" + event.dataVariable + "'', ''" + applicationId + "'')"); output.append("</script>"); } // wrap wih div tag output.append("<div id=\"" + getId() + "\">"); try{ properties.context = context; if(!properties.hasUnresolvedVariable()) drawInternal(context, output); }finally{ properties.context = null; } output.append("</div>"); return output.toString(); } |
if (single!=null) { if (single.booleanValue()==true) { if(value instanceof List) { List l = (List) value; if (l.size()==0) value=null; else value=l.get(0); } if(asString!=null && asString.booleanValue() && value instanceof Node) value = ((Node) value).getStringValue(); } else { if(! (value instanceof List) ) { List l = null; if (value==null) { l = new ArrayList(0); } else { l = new ArrayList(1); l.add(value); } value = l; } } | switch ( determineReturnType() ) { case RETURN_NODE_LIST: value = valueAsList(value); break; case RETURN_FIRST_NODE: value = valueAsSingle(value); break; case RETURN_STRING_LIST: value = nodeListToStringList(valueAsList(value)); break; case RETURN_DELIMITED_STRING_LIST: value = joinDelimitedElements(nodeListToStringList(valueAsList(value))); break; case RETURN_FIRST_AS_STRING: value = singleValueAsString(valueAsSingle(value)); break; | public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException { if (var == null) { throw new MissingAttributeException( "var" ); } if (select == null) { throw new MissingAttributeException( "select" ); } Object xpathContext = getXPathContext(); Object value = null; try { if(single!=null && single.booleanValue()==true) { value = select.selectSingleNode(xpathContext); } else { value = select.evaluate(xpathContext); } } catch (JaxenException e) { throw new JellyTagException(e); } if (value instanceof List) { // sort the list if xpCmp is set. if (xpCmp != null && (xpCmp.getXpath() != null)) { Collections.sort((List)value, xpCmp); } } if (single!=null) { if (single.booleanValue()==true) { if(value instanceof List) { List l = (List) value; if (l.size()==0) value=null; else value=l.get(0); } if(asString!=null && asString.booleanValue() && value instanceof Node) value = ((Node) value).getStringValue(); } else { // single == false if(! (value instanceof List) ) { List l = null; if (value==null) { l = new ArrayList(0); } else { l = new ArrayList(1); l.add(value); } value = l; } } } //log.info( "Evaluated xpath: " + select + " as: " + value + " of type: " + value.getClass().getName() ); context.setVariable(var, value); } |
if(asString) this.single = new Boolean(asString); | public void setAsString(boolean asString) { if(asString) this.single = new Boolean(asString); this.asString = new Boolean(asString); } |
|
Object answer = null; | Object answer = taglibs.get(namespaceURI); | public TagLibrary getTagLibrary(String namespaceURI) { Object answer = null; if ( getInherit() && getParent() != null ) { answer = getParent().getTagLibrary( namespaceURI ); } if ( answer == null ) { answer = taglibs.get(namespaceURI); } if ( answer instanceof TagLibrary ) { return (TagLibrary) answer; } else if ( answer instanceof String ) { String className = (String) answer; Class theClass = null; try { theClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { log.error("Could not find the class: " + className, e); } if ( theClass != null ) { try { Object object = theClass.newInstance(); if (object instanceof TagLibrary) { taglibs.put(namespaceURI, object); return (TagLibrary) object; } else { log.error( "The tag library object mapped to: " + namespaceURI + " is not a TagLibrary. Object = " + object); } } catch (Exception e) { log.error( "Could not instantiate instance of class: " + className + ". Reason: " + e, e); } } } return null; } |
if ( getInherit() && getParent() != null ) { answer = getParent().getTagLibrary( namespaceURI ); } if ( answer == null ) { answer = taglibs.get(namespaceURI); | if ( answer == null && parent != null ) { answer = parent.getTagLibrary( namespaceURI ); | public TagLibrary getTagLibrary(String namespaceURI) { Object answer = null; if ( getInherit() && getParent() != null ) { answer = getParent().getTagLibrary( namespaceURI ); } if ( answer == null ) { answer = taglibs.get(namespaceURI); } if ( answer instanceof TagLibrary ) { return (TagLibrary) answer; } else if ( answer instanceof String ) { String className = (String) answer; Class theClass = null; try { theClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { log.error("Could not find the class: " + className, e); } if ( theClass != null ) { try { Object object = theClass.newInstance(); if (object instanceof TagLibrary) { taglibs.put(namespaceURI, object); return (TagLibrary) object; } else { log.error( "The tag library object mapped to: " + namespaceURI + " is not a TagLibrary. Object = " + object); } } catch (Exception e) { log.error( "Could not instantiate instance of class: " + className + ". Reason: " + e, e); } } } return null; } |
return taglibs.containsKey( namespaceURI ); | boolean answer = taglibs.containsKey( namespaceURI ); if (answer) { return true; } else if ( parent != null ) { return parent.isTagLibraryRegistered(namespaceURI); } else { return false; } | public boolean isTagLibraryRegistered(String namespaceURI) { return taglibs.containsKey( namespaceURI ); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.