bugged
stringlengths
6
599k
fixed
stringlengths
10
599k
__index_level_0__
int64
0
1.13M
public DBTree(List initialDatabases) throws ArchitectException { super(new DBTreeModel(initialDatabases)); setRootVisible(false); setShowsRootHandles(true); ds = new DragSource(); DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer (this, DnDConstants.ACTION_COPY, new DBTreeDragGestureListener()); setupPropDialog(); popup = setupPopupMenu(); addMouseListener(new PopupListener()); }
public DBTree(List initialDatabases) throws ArchitectException { super(new DBTreeModel(initialDatabases)); setRootVisible(false); setShowsRootHandles(true); ds = new DragSource(); DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer (this, DnDConstants.ACTION_COPY, new DBTreeDragGestureListener()); setupPropDialog(); popup = setupPopupMenu(); addMouseListener(new PopupListener()); }
1,109,072
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 dumb Swing can't requestFocus until shown bug //this one seems to throw a harmless exception in certain versions of the linux JRE try{ SwingUtilities.invokeLater( new Runnable(){ public void run() { genoFileField.requestFocus(); }}); }catch (RuntimeException re){ } //this one seems to really fuck over the 1.3 version of the windows JRE //in short: Java sucks. /*genoFileField.dispatchEvent( new FocusEvent( genoFileField, FocusEvent.FOCUS_GAINED, false ) );*/ 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); if (ft != HMP){ filePanel.add(botFilePanel); } filePanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); contents.add(filePanel); JPanel compDistPanel = new JPanel(); maxComparisonDistField = new NumberTextField("500",4, false); compDistPanel.add(new JLabel("Ignore pairwise comparisons of markers >")); compDistPanel.add(maxComparisonDistField); compDistPanel.add(new JLabel("kb apart.")); contents.add(compDistPanel); doGB = new JCheckBox();//show gbrowse pic from hapmap website? doGB.setSelected(false); if (ft == HMP){ JPanel gBrowsePanel = new JPanel(); gBrowsePanel.add(doGB); gBrowsePanel.add(new JLabel("Download and show HapMap gene track? (requires internet connection)")); contents.add(gBrowsePanel); } doTDT = new JCheckBox();//"Do association test?"); doTDT.setSelected(false); doTDT.setActionCommand("tdt"); doTDT.addActionListener(this); trioButton = new JRadioButton("Family trio data", true); trioButton.setEnabled(false); ccButton = new JRadioButton("Case/Control data"); ccButton.setEnabled(false); ButtonGroup group = new ButtonGroup(); group.add(trioButton); group.add(ccButton); if (ft == PED){ JPanel tdtOptsPanel = new JPanel(); JPanel tdtCheckBoxPanel = new JPanel(); tdtCheckBoxPanel.add(doTDT); tdtCheckBoxPanel.add(new JLabel("Do association test?")); tdtOptsPanel.add(trioButton); tdtOptsPanel.add(ccButton); contents.add(tdtCheckBoxPanel); contents.add(tdtOptsPanel); } 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(); }
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 dumb Swing can't requestFocus until shown bug //this one seems to throw a harmless exception in certain versions of the linux JRE try{ SwingUtilities.invokeLater( new Runnable(){ public void run() { genoFileField.requestFocus(); }}); }catch (RuntimeException re){ } //this one seems to really fuck over the 1.3 version of the windows JRE //in short: Java sucks. /*genoFileField.dispatchEvent( new FocusEvent( genoFileField, FocusEvent.FOCUS_GAINED, false ) );*/ 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); if (ft != HMP){ filePanel.add(botFilePanel); } filePanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); contents.add(filePanel); JPanel compDistPanel = new JPanel(); maxComparisonDistField = new NumberTextField("500",4, false); compDistPanel.add(new JLabel("Ignore pairwise comparisons of markers >")); compDistPanel.add(maxComparisonDistField); compDistPanel.add(new JLabel("kb apart.")); contents.add(compDistPanel); doGB = new JCheckBox();//show gbrowse pic from hapmap website? doGB.setSelected(false); if (ft == HMP){ JPanel gBrowsePanel = new JPanel(); gBrowsePanel.add(doGB); gBrowsePanel.add(new JLabel("Download and show HapMap info track? (requires internet connection)")); contents.add(gBrowsePanel); } doTDT = new JCheckBox();//"Do association test?"); doTDT.setSelected(false); doTDT.setActionCommand("tdt"); doTDT.addActionListener(this); trioButton = new JRadioButton("Family trio data", true); trioButton.setEnabled(false); ccButton = new JRadioButton("Case/Control data"); ccButton.setEnabled(false); ButtonGroup group = new ButtonGroup(); group.add(trioButton); group.add(ccButton); if (ft == PED){ JPanel tdtOptsPanel = new JPanel(); JPanel tdtCheckBoxPanel = new JPanel(); tdtCheckBoxPanel.add(doTDT); tdtCheckBoxPanel.add(new JLabel("Do association test?")); tdtOptsPanel.add(trioButton); tdtOptsPanel.add(ccButton); contents.add(tdtCheckBoxPanel); contents.add(tdtOptsPanel); } 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(); }
1,109,074
public void saveResultToFile(File outFile) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); bw.write("#tagging with r^2 cutoff: " + minRSquared); bw.newLine(); bw.write("#captured " + taggedSoFar + " of " + snps.size() +" alleles with mean r^2 of " + Util.roundDouble(meanRSq, 3)); bw.newLine(); bw.write("#captured " + percentOver8 + " percent of alleles with r^2 > 0.8"); bw.newLine(); bw.write("#using " + getTagSNPs().size() + " SNPs in " + tags.size() + " tests."); bw.newLine(); bw.write("Marker\tBest Test\tr^2 w/test"); bw.newLine(); for (int i = 0; i < snps.size(); i++) { StringBuffer line = new StringBuffer(); SNP snp = (SNP) snps.elementAt(i); line.append(snp.getName()).append("\t"); TagSequence theTag = snp.getBestTag(); if(theTag != null) { line.append(theTag.getName()).append("\t"); line.append(getPairwiseCompRsq(snp,theTag.getSequence())).append("\t"); } bw.write(line.toString()); bw.newLine(); } bw.newLine(); bw.write("Test\tAlleles Captured"); bw.newLine(); for(int i=0;i<tags.size();i++) { StringBuffer line = new StringBuffer(); TagSequence theTag = (TagSequence) tags.get(i); line.append(theTag.getName()).append("\t"); Vector tagged = theTag.getBestTagged(); for (int j = 0; j < tagged.size(); j++) { VariantSequence varSeq = (VariantSequence) tagged.elementAt(j); if(j !=0){ line.append(","); } line.append(varSeq.getName()); } bw.write(line.toString()); bw.newLine(); } bw.close(); }
public void saveResultToFile(File outFile) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); bw.write("#tagging with r^2 cutoff: " + minRSquared); bw.newLine(); bw.write("#captured " + taggedSoFar + " of " + snps.size() +" alleles with mean r^2 of " + Util.roundDouble(meanRSq, 3)); bw.newLine(); bw.write("#captured " + percentOver8 + " percent of alleles with r^2 > 0.8"); bw.newLine(); bw.write("#using " + getTagSNPs().size() + " Tag SNPs in " + tags.size() + " tests."); bw.newLine(); bw.write("Marker\tBest Test\tr^2 w/test"); bw.newLine(); for (int i = 0; i < snps.size(); i++) { StringBuffer line = new StringBuffer(); SNP snp = (SNP) snps.elementAt(i); line.append(snp.getName()).append("\t"); TagSequence theTag = snp.getBestTag(); if(theTag != null) { line.append(theTag.getName()).append("\t"); line.append(getPairwiseCompRsq(snp,theTag.getSequence())).append("\t"); } bw.write(line.toString()); bw.newLine(); } bw.newLine(); bw.write("Test\tAlleles Captured"); bw.newLine(); for(int i=0;i<tags.size();i++) { StringBuffer line = new StringBuffer(); TagSequence theTag = (TagSequence) tags.get(i); line.append(theTag.getName()).append("\t"); Vector tagged = theTag.getBestTagged(); for (int j = 0; j < tagged.size(); j++) { VariantSequence varSeq = (VariantSequence) tagged.elementAt(j); if(j !=0){ line.append(","); } line.append(varSeq.getName()); } bw.write(line.toString()); bw.newLine(); } bw.close(); }
1,109,075
public void saveResultToFile(File outFile) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); bw.write("#tagging with r^2 cutoff: " + minRSquared); bw.newLine(); bw.write("#captured " + taggedSoFar + " of " + snps.size() +" alleles with mean r^2 of " + Util.roundDouble(meanRSq, 3)); bw.newLine(); bw.write("#captured " + percentOver8 + " percent of alleles with r^2 > 0.8"); bw.newLine(); bw.write("#using " + getTagSNPs().size() + " SNPs in " + tags.size() + " tests."); bw.newLine(); bw.write("Marker\tBest Test\tr^2 w/test"); bw.newLine(); for (int i = 0; i < snps.size(); i++) { StringBuffer line = new StringBuffer(); SNP snp = (SNP) snps.elementAt(i); line.append(snp.getName()).append("\t"); TagSequence theTag = snp.getBestTag(); if(theTag != null) { line.append(theTag.getName()).append("\t"); line.append(getPairwiseCompRsq(snp,theTag.getSequence())).append("\t"); } bw.write(line.toString()); bw.newLine(); } bw.newLine(); bw.write("Test\tAlleles Captured"); bw.newLine(); for(int i=0;i<tags.size();i++) { StringBuffer line = new StringBuffer(); TagSequence theTag = (TagSequence) tags.get(i); line.append(theTag.getName()).append("\t"); Vector tagged = theTag.getBestTagged(); for (int j = 0; j < tagged.size(); j++) { VariantSequence varSeq = (VariantSequence) tagged.elementAt(j); if(j !=0){ line.append(","); } line.append(varSeq.getName()); } bw.write(line.toString()); bw.newLine(); } bw.close(); }
public void saveResultToFile(File outFile) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); bw.write("#tagging with r^2 cutoff: " + minRSquared); bw.newLine(); bw.write("#captured " + taggedSoFar + " of " + snps.size() +" alleles with mean r^2 of " + Util.roundDouble(meanRSq, 3)); bw.newLine(); bw.write("#captured " + percentOver8 + " percent of alleles with r^2 > 0.8"); bw.newLine(); bw.write("#using " + getTagSNPs().size() + " SNPs in " + tags.size() + " tests."); bw.newLine(); bw.write("Allele\tBest Test\tr^2 w/test"); bw.newLine(); for (int i = 0; i < snps.size(); i++) { StringBuffer line = new StringBuffer(); SNP snp = (SNP) snps.elementAt(i); line.append(snp.getName()).append("\t"); TagSequence theTag = snp.getBestTag(); if(theTag != null) { line.append(theTag.getName()).append("\t"); line.append(getPairwiseCompRsq(snp,theTag.getSequence())).append("\t"); } bw.write(line.toString()); bw.newLine(); } bw.newLine(); bw.write("Test\tAlleles Captured"); bw.newLine(); for(int i=0;i<tags.size();i++) { StringBuffer line = new StringBuffer(); TagSequence theTag = (TagSequence) tags.get(i); line.append(theTag.getName()).append("\t"); Vector tagged = theTag.getBestTagged(); for (int j = 0; j < tagged.size(); j++) { VariantSequence varSeq = (VariantSequence) tagged.elementAt(j); if(j !=0){ line.append(","); } line.append(varSeq.getName()); } bw.write(line.toString()); bw.newLine(); } bw.close(); }
1,109,076
public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side if (info){ g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+90,5,labeloffset+scale-5,scale-90); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); g.drawLine(labeloffset+25+y*30, 5+y*30,(int)(labeloffset+90+xOrYDist),(int)(5+xOrYDist)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } }
public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side if (info){ g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+90,5,labeloffset+scale-5,scale-90); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); g.drawLine(labeloffset+25+y*30, 5+y*30,(int)(labeloffset+90+xOrYDist),(int)(5+xOrYDist)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } }
1,109,077
public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side if (info){ g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+90,5,labeloffset+scale-5,scale-90); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); g.drawLine(labeloffset+25+y*30, 5+y*30,(int)(labeloffset+90+xOrYDist),(int)(5+xOrYDist)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } }
public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side if (info){ g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+90,5,labeloffset+scale-5,scale-90); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); g.drawLine(labeloffset+25+y*30, 5+y*30,(int)(labeloffset+90+xOrYDist),(int)(5+xOrYDist)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(nf.format(Float.parseFloat(st.nextToken()))); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } }
1,109,078
public void haploDraw(Graphics gr, boolean myuseThickness, int mycolorThresh, int mycrossThinThresh, int mycrossThickThresh, double[] gapDPrime, Haplotype[][] hapsInBlocks){ NumberFormat nf = NumberFormat.getInstance(); NumberFormat nfMulti = NumberFormat.getInstance(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); Graphics2D g = (Graphics2D) gr; final BasicStroke stroke = new BasicStroke(1.0f); final BasicStroke wideStroke = new BasicStroke(2.0f); final int verticalOffset = 43; final Font nonMonoFont = new Font("Lucida Bright", Font.PLAIN, 12); final Font regFont = new Font("Lucida Sans Typewriter", Font.PLAIN, 12); final Font smallFont = new Font("Lucida Sans Typewriter", Font.PLAIN, 7); final Font boldFont = new Font("Lucida Bright", Font.BOLD, 12); FontMetrics regfm = g.getFontMetrics(regFont); FontMetrics nonMonofm = g.getFontMetrics(nonMonoFont); FontMetrics boldfm = g.getFontMetrics(boldFont); String theHap = new String(); int x = 10; int y = verticalOffset; int totalWidth = 0; int[][]lookupPos = new int[hapsInBlocks.length][]; for (int p = 0; p < lookupPos.length; p++){ lookupPos[p] = new int[hapsInBlocks[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][hapsInBlocks[p][q].getListOrder()] = q; //System.out.println(p + " " + q + " " + hapsInBlocks[p][q].getListOrder()); } } Dimension theDimension = haploGetPreferredSize(hapsInBlocks, gr); int windowX = (int)theDimension.getWidth(); int windowY = (int)theDimension.getHeight(); g.setColor(Color.white); g.fillRect(0,0,windowX,windowY); g.setColor(Color.black); for (int i = 0; i < hapsInBlocks.length; i++){ int[] markerNums = hapsInBlocks[i][0].getMarkers(); boolean[] tags = hapsInBlocks[i][0].getTags(); int headerX = x; for (int z = 0; z < markerNums.length; z++){ //put tag snps in red if (tags[z]) { g.setColor(Color.red); } //write labels with more than one digit vertically if (markerNums[z]+1 < 10){ g.setFont(regFont); g.drawString(String.valueOf(markerNums[z]+1), headerX, 18); headerX += (regfm.stringWidth(String.valueOf(markerNums[z]+1))); }else { int ones = (markerNums[z]+1)%10; int tens = (((markerNums[z]+1)-ones)%100)/10; g.setFont(regFont); g.drawString(String.valueOf(ones), headerX, 18); g.setFont(smallFont); g.drawString(String.valueOf(tens), headerX-2, 20-regfm.getAscent()); headerX += (regfm.stringWidth(String.valueOf(ones))); } g.setColor(Color.black); } for (int j = 0; j < hapsInBlocks[i].length; j++){ int curHapNum = lookupPos[i][j]; theHap = new String(); String thePercentage = new String(); int[] theGeno = hapsInBlocks[i][curHapNum].getGeno(); for (int k = 0; k < theGeno.length; k++){ //if we don't know what one of the alleles for a marker is, use "x" if (theGeno[k] == 8){ theHap += "x"; }else{ theHap += theGeno[k]; } } //draw the haplotype in mono font g.setFont(regFont); g.drawString(theHap, x, y); //draw the percentage value in non mono font thePercentage = " (" + nf.format(hapsInBlocks[i][curHapNum].getPercentage()) + ")"; g.setFont(nonMonoFont); g.drawString(thePercentage, x+regfm.stringWidth(theHap), y); totalWidth = regfm.stringWidth(theHap) + nonMonofm.stringWidth(thePercentage); if (i < hapsInBlocks.length - 1){ //draw crossovers for (int crossCount = 0; crossCount < hapsInBlocks[i+1].length; crossCount++){ double crossVal = hapsInBlocks[i][curHapNum].getCrossover(crossCount); if (myuseThickness){ //draw thin and thick lines if (crossVal*100 > mycrossThinThresh){ if (crossVal*100 > mycrossThickThresh){ g.setStroke(wideStroke); }else{ g.setStroke(stroke); } //this arcane formula draws lines neatly from one hap to another g.draw(new Line2D.Double((x+totalWidth+3), (y-regfm.getAscent()/2), (x+totalWidth+37), (verticalOffset-regfm.getAscent()/2+((regfm.getHeight()+5)*hapsInBlocks[i+1][crossCount].getListOrder())))); } }else{ //draw colored lines if(crossVal*100 > mycolorThresh){ g.setStroke(stroke); double overThresh = crossVal*100 - mycolorThresh; float lineRed, lineGreen, lineBlue; if(overThresh < (50-mycolorThresh)/2){ //cold colors lineRed=0.0f; lineBlue=new Double(0.9-((overThresh/((50-mycolorThresh)/2))*0.9)).floatValue(); lineGreen=0.9f-lineBlue; }else{ //hot colors lineBlue=0.0f; lineRed=new Double(((overThresh-(50-mycolorThresh)/2)/((50-mycolorThresh)/2))*0.9).floatValue(); lineGreen=0.9f-lineRed; } Color lineColor = new Color(lineRed, lineGreen, lineBlue); g.setColor(lineColor); g.setStroke(new BasicStroke(1.5f)); g.draw(new Line2D.Double((x+totalWidth+3), (y-regfm.getAscent()/2), (x+totalWidth+37), (verticalOffset-regfm.getAscent()/2+((regfm.getHeight()+5)*hapsInBlocks[i+1][crossCount].getListOrder())))); g.setColor(Color.black); g.setStroke(stroke); } } } } y += (regfm.getHeight()+5); } //add the multilocus d prime if appropriate if (i < hapsInBlocks.length - 1){ int multiX = x +totalWidth+3; g.setStroke(wideStroke); g.setFont(boldFont); g.drawRect(multiX, windowY-boldfm.getAscent()-4, boldfm.stringWidth("8.88")+3, boldfm.getAscent()+3); g.drawString(String.valueOf(nfMulti.format(gapDPrime[i])), multiX+2, windowY - 3); g.setStroke(stroke); } x += (totalWidth + 40); y = verticalOffset; } }
public void haploDraw(Graphics gr, boolean myuseThickness, int mycolorThresh, int mycrossThinThresh, int mycrossThickThresh, double[] gapDPrime, Haplotype[][] hapsInBlocks){ NumberFormat nf = NumberFormat.getInstance(); NumberFormat nfMulti = NumberFormat.getInstance(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); Graphics2D g = (Graphics2D) gr; final BasicStroke stroke = new BasicStroke(1.0f); final BasicStroke wideStroke = new BasicStroke(2.0f); final int verticalOffset = 43; final Font nonMonoFont = new Font("Lucida Bright", Font.PLAIN, 12); final Font regFont = new Font("Lucida Sans Typewriter", Font.PLAIN, 12); final Font smallFont = new Font("Lucida Sans Typewriter", Font.PLAIN, 7); final Font boldFont = new Font("Lucida Bright", Font.BOLD, 12); FontMetrics regfm = g.getFontMetrics(regFont); FontMetrics nonMonofm = g.getFontMetrics(nonMonoFont); FontMetrics boldfm = g.getFontMetrics(boldFont); String theHap = new String(); int x = 10; int y = verticalOffset; int totalWidth = 0; int[][]lookupPos = new int[hapsInBlocks.length][]; for (int p = 0; p < lookupPos.length; p++){ lookupPos[p] = new int[hapsInBlocks[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][hapsInBlocks[p][q].getListOrder()] = q; //System.out.println(p + " " + q + " " + hapsInBlocks[p][q].getListOrder()); } } Dimension theDimension = haploGetPreferredSize(hapsInBlocks, gr); int windowX = (int)theDimension.getWidth(); int windowY = (int)theDimension.getHeight(); g.setColor(Color.white); g.fillRect(0,0,windowX,windowY); g.setColor(Color.black); for (int i = 0; i < hapsInBlocks.length; i++){ int[] markerNums = hapsInBlocks[i][0].getMarkers(); boolean[] tags = hapsInBlocks[i][0].getTags(); int headerX = x; for (int z = 0; z < markerNums.length; z++){ //put tag snps in red if (tags[z]) { g.setColor(Color.red); } //write labels with more than one digit vertically if (markerNums[z]+1 < 10){ g.setFont(regFont); g.drawString(String.valueOf(markerNums[z]+1), headerX, 18); headerX += (regfm.stringWidth(String.valueOf(markerNums[z]+1))); }else { int ones = (markerNums[z]+1)%10; int tens = (((markerNums[z]+1)-ones)%100)/10; g.setFont(regFont); g.drawString(String.valueOf(ones), headerX, 18); g.setFont(smallFont); g.drawString(String.valueOf(tens), headerX-2, 20-regfm.getAscent()); headerX += (regfm.stringWidth(String.valueOf(ones))); } g.setColor(Color.black); } for (int j = 0; j < hapsInBlocks[i].length; j++){ int curHapNum = lookupPos[i][j]; theHap = new String(); String thePercentage = new String(); int[] theGeno = hapsInBlocks[i][curHapNum].getGeno(); for (int k = 0; k < theGeno.length; k++){ //if we don't know what one of the alleles for a marker is, use "x" if (theGeno[k] == 8){ theHap += "x"; }else{ theHap += theGeno[k]; } } //draw the haplotype in mono font g.setFont(regFont); g.drawString(theHap, x, y); //draw the percentage value in non mono font thePercentage = " (" + nf.format(hapsInBlocks[i][curHapNum].getPercentage()) + ")"; g.setFont(nonMonoFont); g.drawString(thePercentage, x+regfm.stringWidth(theHap), y); totalWidth = regfm.stringWidth(theHap) + nonMonofm.stringWidth(thePercentage); if (i < hapsInBlocks.length - 1){ //draw crossovers for (int crossCount = 0; crossCount < hapsInBlocks[i+1].length; crossCount++){ double crossVal = hapsInBlocks[i][curHapNum].getCrossover(crossCount); if (myuseThickness){ //draw thin and thick lines if (crossVal*100 > mycrossThinThresh){ if (crossVal*100 > mycrossThickThresh){ g.setStroke(wideStroke); }else{ g.setStroke(stroke); } //this arcane formula draws lines neatly from one hap to another g.draw(new Line2D.Double((x+totalWidth+3), (y-regfm.getAscent()/2), (x+totalWidth+37), (verticalOffset-regfm.getAscent()/2+((regfm.getHeight()+5)*hapsInBlocks[i+1][crossCount].getListOrder())))); } }else{ //draw colored lines if(crossVal*100 > mycolorThresh){ g.setStroke(stroke); double overThresh = crossVal*100 - mycolorThresh; float lineRed, lineGreen, lineBlue; if(overThresh < (50-mycolorThresh)/2){ //cold colors lineRed=0.0f; lineBlue=new Double(0.9-((overThresh/((50-mycolorThresh)/2))*0.9)).floatValue(); lineGreen=0.9f-lineBlue; }else{ //hot colors lineBlue=0.0f; lineRed=new Double(((overThresh-(50-mycolorThresh)/2)/((50-mycolorThresh)/2))*0.9).floatValue(); lineGreen=0.9f-lineRed; } Color lineColor = new Color(lineRed, lineGreen, lineBlue); g.setColor(lineColor); g.setStroke(new BasicStroke(1.5f)); g.draw(new Line2D.Double((x+totalWidth+3), (y-regfm.getAscent()/2), (x+totalWidth+37), (verticalOffset-regfm.getAscent()/2+((regfm.getHeight()+5)*hapsInBlocks[i+1][crossCount].getListOrder())))); g.setColor(Color.black); g.setStroke(stroke); } } } } y += (regfm.getHeight()+5); } //add the multilocus d prime if appropriate if (i < hapsInBlocks.length - 1){ int multiX = x +totalWidth+3; g.setStroke(wideStroke); g.setFont(boldFont); g.drawRect(multiX, windowY-boldfm.getAscent()-4, boldfm.stringWidth("8.88")+3, boldfm.getAscent()+3); g.drawString(String.valueOf(nfMulti.format(gapDPrime[i])), multiX+2, windowY - 3); g.setStroke(stroke); } x += (totalWidth + 40); y = verticalOffset; } }
1,109,079
public static LocalizationContext getLocalizationContext(JellyContext jc, String basename) { LocalizationContext locCtxt = null; ResourceBundle bundle = null; if ((basename == null) || basename.equals("")) { return new LocalizationContext(); } // Try preferred locales Locale pref = null; { Object tmp = jc.getVariable(Config.FMT_LOCALE); if (tmp != null && tmp instanceof Locale) { pref = (Locale) tmp; } } if (pref != null) { // Preferred locale is application-based bundle = findMatch(basename, pref, jc.getClassLoader()); if (bundle != null) { locCtxt = new LocalizationContext(bundle, pref); } } if (locCtxt == null) { // No match found with preferred locales, try using fallback locale { Object tmp = jc.getVariable(Config.FMT_FALLBACK_LOCALE); if (tmp != null && tmp instanceof Locale) { pref = (Locale) tmp; } } if (pref != null) { bundle = findMatch(basename, pref, jc.getClassLoader()); if (bundle != null) { locCtxt = new LocalizationContext(bundle, pref); } } } if (locCtxt == null) { // try using the root resource bundle with the given basename try { bundle = ResourceBundle.getBundle(basename, EMPTY_LOCALE, jc.getClassLoader()); if (bundle != null) { locCtxt = new LocalizationContext(bundle, null); } } catch (MissingResourceException mre) { // do nothing } } if (locCtxt != null) { // set response locale if (locCtxt.getLocale() != null) { // TODO // SetLocaleSupport.setResponseLocale(jc, locCtxt.getLocale()); } } else { // create empty localization context locCtxt = new LocalizationContext(); } return locCtxt; }
public static LocalizationContext getLocalizationContext(JellyContext jc, String basename) { LocalizationContext locCtxt = null; ResourceBundle bundle = null; if ((basename == null) || basename.equals("")) { return new LocalizationContext(); } // Try preferred locales Locale pref = null; { Object tmp = jc.getVariable(Config.FMT_LOCALE); if (tmp != null && tmp instanceof Locale) { pref = (Locale) tmp; } } if (pref != null) { // Preferred locale is application-based bundle = findMatch(basename, pref, jc.getClassLoader()); if (bundle != null) { locCtxt = new LocalizationContext(bundle, pref); } } if (locCtxt == null) { // No match found with preferred locales, try using fallback locale { Object tmp = jc.getVariable(Config.FMT_FALLBACK_LOCALE); if (tmp != null && tmp instanceof Locale) { pref = (Locale) tmp; } } if (pref != null) { bundle = findMatch(basename, pref, jc.getClassLoader()); if (bundle != null) { locCtxt = new LocalizationContext(bundle, pref); } } } if (locCtxt == null) { // try using the root resource bundle with the given basename try { bundle = ResourceBundle.getBundle(basename, EMPTY_LOCALE, jc.getClassLoader()); if (bundle != null) { locCtxt = new LocalizationContext(bundle, null); } } catch (MissingResourceException mre) { // do nothing } } if (locCtxt != null) { // set response locale if (locCtxt.getLocale() != null) { // TODO // SetLocaleSupport.setResponseLocale(jc, locCtxt.getLocale()); } } else { // create empty localization context locCtxt = new LocalizationContext(); } return locCtxt; }
1,109,081
private String generateUniqueColumnName(SQLColumn column, SQLTable table) { return column.getName() + "_1"; // XXX: fix this to be better }
private static String generateUniqueColumnName(SQLColumn column, SQLTable table) { return column.getName() + "_1"; // XXX: fix this to be better }
1,109,082
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,083
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,084
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,085
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,086
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,087
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,088
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,089
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { logger.debug("777777777777 not instance of TablePane."); if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
public void itemSelected(SelectionEvent e) { // what address am I? logger.debug("00000000000 object hash code: " + super.hashCode()); // ignore events unless active logger.debug("11111111ITEM SELECTED: " + e); if (!active) { logger.debug("222222222 not active."); return; } else { logger.debug("222222222 ACTIVE!!!."); } Selectable s = e.getSelectableSource(); // don't care when tables (or anything else) are deselected if (!s.isSelected()) { logger.debug("333333333 not selected."); return; } if (s instanceof TablePane) { logger.debug("4444444444444 instance of TablePane."); if (pkTable == null) { pkTable = (TablePane) s; logger.debug("555555555555 Creating relationship: PK Table is "+pkTable); } else { fkTable = (TablePane) s; logger.debug("66666666666666 Creating relationship: FK Table is "+fkTable); doCreateRelationship(); // this might fail, but still set things back to "normal" pp.setCursor(null); logger.debug("66666666666666 setting active to FALSE!"); active = false; } } else { if (logger.isDebugEnabled()) logger.debug("The user clicked on a non-table component: "+s); } }
1,109,090
public void doEM(int[] theBlock) throws HaploViewException{ //break up large blocks if needed int[] block_size; if (theBlock.length < 9){ block_size = new int[1]; block_size[0] = theBlock.length; } else { //some base-8 arithmetic int ones = theBlock.length%8; int eights = (theBlock.length - ones)/8; if (ones == 0){ block_size = new int[eights]; for (int i = 0; i < eights; i++){ block_size[i]=8; } } else { block_size = new int[eights+1]; for (int i = 0; i < eights-1; i++){ block_size[i]=8; } block_size[eights-1] = (8+ones)/2; block_size[eights] = 8+ones-block_size[eights-1]; } } byte[] thisHap; Vector inputHaploSingletons = new Vector(); Vector inputHaploTrios = new Vector(); Vector affSingletons = new Vector(); Vector affTrios = new Vector(); //whichVector[i] stores a value which indicates which vector chromosome i's genotype should go in //1 indicates inputHaploSingletons (singletons), 2 indicates inputHaploTrios, //3 indicates a person from a broken trio who is treated as a singleton //0 indicates none (too much missing data) int[] whichVector = new int[chromosomes.size()]; for(int i=0;i<numTrios*4; i+=4) { Chromosome parentAFirst = (Chromosome) chromosomes.elementAt(i); Chromosome parentASecond = (Chromosome) chromosomes.elementAt(i+1); Chromosome parentBFirst = (Chromosome) chromosomes.elementAt(i+2); Chromosome parentBSecond = (Chromosome) chromosomes.elementAt(i+3); boolean tooManyMissingInASegmentA = false; boolean tooManyMissingInASegmentB = false; int totalMissingA = 0; int totalMissingB = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missingA = 0; int missingB = 0; for (int j = 0; j < block_size[n]; j++){ byte AFirstGeno = parentAFirst.getGenotype(theBlock[segmentShift+j]); byte ASecondGeno = parentASecond.getGenotype(theBlock[segmentShift+j]); byte BFirstGeno = parentBFirst.getGenotype(theBlock[segmentShift+j]); byte BSecondGeno = parentBSecond.getGenotype(theBlock[segmentShift+j]); if(AFirstGeno == 0 || ASecondGeno == 0) missingA++; if(BFirstGeno == 0 || BSecondGeno == 0) missingB++; } segmentShift += block_size[n]; if (missingA >= MISSINGLIMIT){ tooManyMissingInASegmentA = true; } if (missingB >= MISSINGLIMIT){ tooManyMissingInASegmentB = true; } totalMissingA += missingA; totalMissingB += missingB; } if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3 && !tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //both parents are good so all 4 chroms are added as a trio whichVector[i] = 2; whichVector[i+1] = 2; whichVector[i+2] = 2; whichVector[i+3] = 2; } else if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3) { //first person good, so he's added as a singleton, other parent is dropped whichVector[i] = 3; whichVector[i+1] =3; whichVector[i+2] =0; whichVector[i+3]=0; } else if(!tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //second person good, so he's added as a singleton, other parent is dropped whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =3; whichVector[i+3]=3; } else { //both people have too much missing data so neither is used whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =0; whichVector[i+3]=0; } } for (int i = numTrios*4; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); boolean tooManyMissingInASegment = false; int totalMissing = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missing = 0; for (int j = 0; j < block_size[n]; j++){ byte theGeno = thisChrom.getGenotype(theBlock[segmentShift+j]); byte nextGeno = nextChrom.getGenotype(theBlock[segmentShift+j]); if(theGeno == 0 || nextGeno == 0) missing++; } segmentShift += block_size[n]; if (missing >= MISSINGLIMIT){ tooManyMissingInASegment = true; } totalMissing += missing; } //we want to use chromosomes without too many missing genotypes in a given //subsegment (first term) or without too many missing genotypes in the //whole block (second term) if (!tooManyMissingInASegment && totalMissing <= 1+theBlock.length/3){ whichVector[i-1] = 1; whichVector[i] = 1; } } //we only want to add an affected status every other chromosome, so we flip this boolean each time boolean addAff = true; for (int i = 0; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); if(whichVector[i] > 0) { thisHap = new byte[theBlock.length]; for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getMarker(theBlock[j]).getMinor(); byte theGeno = thisChrom.getGenotype(theBlock[j]); if (theGeno >= 5){ thisHap[j] = 'h'; } else { if (theGeno == a1){ thisHap[j] = '1'; }else if (theGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } if(whichVector[i] == 1) { inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(thisChrom.getAffected())); } } else if(whichVector[i] ==2) { inputHaploTrios.add(thisHap); if(addAff) { affTrios.add(new Integer(thisChrom.getAffected())); } }else if (whichVector[i] == 3){ inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(0)); } } if(addAff) { addAff = false; } else { addAff =true; } } } int trioCount = inputHaploTrios.size() / 4; inputHaploTrios.addAll(inputHaploSingletons); affTrios.addAll(affSingletons); byte[][] input_haplos = (byte[][])inputHaploTrios.toArray(new byte[0][0]); full_em_breakup(input_haplos, block_size, trioCount, affTrios); }
public void doEM(int[] theBlock) throws HaploViewException{ //break up large blocks if needed int[] block_size; if (theBlock.length < 9){ block_size = new int[1]; block_size[0] = theBlock.length; } else { //some base-8 arithmetic int ones = theBlock.length%8; int eights = (theBlock.length - ones)/8; if (ones == 0){ block_size = new int[eights]; for (int i = 0; i < eights; i++){ block_size[i]=8; } } else { block_size = new int[eights+1]; for (int i = 0; i < eights-1; i++){ block_size[i]=8; } block_size[eights-1] = (8+ones)/2; block_size[eights] = 8+ones-block_size[eights-1]; } } byte[] thisHap; Vector inputHaploSingletons = new Vector(); Vector inputHaploTrios = new Vector(); Vector affSingletons = new Vector(); Vector affTrios = new Vector(); //whichVector[i] stores a value which indicates which vector chromosome i's genotype should go in //1 indicates inputHaploSingletons (singletons), 2 indicates inputHaploTrios, //3 indicates a person from a broken trio who is treated as a singleton //0 indicates none (too much missing data) int[] whichVector = new int[chromosomes.size()]; for(int i=0;i<numTrios*4; i+=4) { Chromosome parentAFirst = (Chromosome) chromosomes.elementAt(i); Chromosome parentASecond = (Chromosome) chromosomes.elementAt(i+1); Chromosome parentBFirst = (Chromosome) chromosomes.elementAt(i+2); Chromosome parentBSecond = (Chromosome) chromosomes.elementAt(i+3); boolean tooManyMissingInASegmentA = false; boolean tooManyMissingInASegmentB = false; int totalMissingA = 0; int totalMissingB = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missingA = 0; int missingB = 0; for (int j = 0; j < block_size[n]; j++){ byte AFirstGeno = parentAFirst.getGenotype(theBlock[segmentShift+j]); byte ASecondGeno = parentASecond.getGenotype(theBlock[segmentShift+j]); byte BFirstGeno = parentBFirst.getGenotype(theBlock[segmentShift+j]); byte BSecondGeno = parentBSecond.getGenotype(theBlock[segmentShift+j]); if(AFirstGeno == 0 || ASecondGeno == 0) missingA++; if(BFirstGeno == 0 || BSecondGeno == 0) missingB++; } segmentShift += block_size[n]; if (missingA >= MISSINGLIMIT){ tooManyMissingInASegmentA = true; } if (missingB >= MISSINGLIMIT){ tooManyMissingInASegmentB = true; } totalMissingA += missingA; totalMissingB += missingB; } if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3 && !tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //both parents are good so all 4 chroms are added as a trio whichVector[i] = 2; whichVector[i+1] = 2; whichVector[i+2] = 2; whichVector[i+3] = 2; } else if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3) { //first person good, so he's added as a singleton, other parent is dropped whichVector[i] = 3; whichVector[i+1] =3; whichVector[i+2] =0; whichVector[i+3]=0; } else if(!tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //second person good, so he's added as a singleton, other parent is dropped whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =3; whichVector[i+3]=3; } else { //both people have too much missing data so neither is used whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =0; whichVector[i+3]=0; } } for (int i = numTrios*4; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); boolean tooManyMissingInASegment = false; int totalMissing = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missing = 0; for (int j = 0; j < block_size[n]; j++){ byte theGeno = thisChrom.getGenotype(theBlock[segmentShift+j]); byte nextGeno = nextChrom.getGenotype(theBlock[segmentShift+j]); if(theGeno == 0 || nextGeno == 0) missing++; } segmentShift += block_size[n]; if (missing >= MISSINGLIMIT){ tooManyMissingInASegment = true; } totalMissing += missing; } //we want to use chromosomes without too many missing genotypes in a given //subsegment (first term) or without too many missing genotypes in the //whole block (second term) if (!tooManyMissingInASegment && totalMissing <= 1+theBlock.length/3){ whichVector[i-1] = 1; whichVector[i] = 1; } } //we only want to add an affected status every other chromosome, so we flip this boolean each time boolean addAff = true; for (int i = 0; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); if(whichVector[i] > 0) { thisHap = new byte[theBlock.length]; for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getMarker(theBlock[j]).getMinor(); byte theGeno = thisChrom.getGenotype(theBlock[j]); if (theGeno >= 5){ thisHap[j] = 'h'; } else { if (theGeno == 0){ thisHap[j] = '0'; }else if (theGeno == a1){ thisHap[j] = '1'; }else if (theGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } if(whichVector[i] == 1) { inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(thisChrom.getAffected())); } } else if(whichVector[i] ==2) { inputHaploTrios.add(thisHap); if(addAff) { affTrios.add(new Integer(thisChrom.getAffected())); } }else if (whichVector[i] == 3){ inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(0)); } } if(addAff) { addAff = false; } else { addAff =true; } } } int trioCount = inputHaploTrios.size() / 4; inputHaploTrios.addAll(inputHaploSingletons); affTrios.addAll(affSingletons); byte[][] input_haplos = (byte[][])inputHaploTrios.toArray(new byte[0][0]); full_em_breakup(input_haplos, block_size, trioCount, affTrios); }
1,109,091
public void doEM(int[] theBlock) throws HaploViewException{ //break up large blocks if needed int[] block_size; if (theBlock.length < 9){ block_size = new int[1]; block_size[0] = theBlock.length; } else { //some base-8 arithmetic int ones = theBlock.length%8; int eights = (theBlock.length - ones)/8; if (ones == 0){ block_size = new int[eights]; for (int i = 0; i < eights; i++){ block_size[i]=8; } } else { block_size = new int[eights+1]; for (int i = 0; i < eights-1; i++){ block_size[i]=8; } block_size[eights-1] = (8+ones)/2; block_size[eights] = 8+ones-block_size[eights-1]; } } byte[] thisHap; Vector inputHaploSingletons = new Vector(); Vector inputHaploTrios = new Vector(); Vector affSingletons = new Vector(); Vector affTrios = new Vector(); //whichVector[i] stores a value which indicates which vector chromosome i's genotype should go in //1 indicates inputHaploSingletons (singletons), 2 indicates inputHaploTrios, //3 indicates a person from a broken trio who is treated as a singleton //0 indicates none (too much missing data) int[] whichVector = new int[chromosomes.size()]; for(int i=0;i<numTrios*4; i+=4) { Chromosome parentAFirst = (Chromosome) chromosomes.elementAt(i); Chromosome parentASecond = (Chromosome) chromosomes.elementAt(i+1); Chromosome parentBFirst = (Chromosome) chromosomes.elementAt(i+2); Chromosome parentBSecond = (Chromosome) chromosomes.elementAt(i+3); boolean tooManyMissingInASegmentA = false; boolean tooManyMissingInASegmentB = false; int totalMissingA = 0; int totalMissingB = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missingA = 0; int missingB = 0; for (int j = 0; j < block_size[n]; j++){ byte AFirstGeno = parentAFirst.getGenotype(theBlock[segmentShift+j]); byte ASecondGeno = parentASecond.getGenotype(theBlock[segmentShift+j]); byte BFirstGeno = parentBFirst.getGenotype(theBlock[segmentShift+j]); byte BSecondGeno = parentBSecond.getGenotype(theBlock[segmentShift+j]); if(AFirstGeno == 0 || ASecondGeno == 0) missingA++; if(BFirstGeno == 0 || BSecondGeno == 0) missingB++; } segmentShift += block_size[n]; if (missingA >= MISSINGLIMIT){ tooManyMissingInASegmentA = true; } if (missingB >= MISSINGLIMIT){ tooManyMissingInASegmentB = true; } totalMissingA += missingA; totalMissingB += missingB; } if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3 && !tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //both parents are good so all 4 chroms are added as a trio whichVector[i] = 2; whichVector[i+1] = 2; whichVector[i+2] = 2; whichVector[i+3] = 2; } else if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3) { //first person good, so he's added as a singleton, other parent is dropped whichVector[i] = 3; whichVector[i+1] =3; whichVector[i+2] =0; whichVector[i+3]=0; } else if(!tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //second person good, so he's added as a singleton, other parent is dropped whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =3; whichVector[i+3]=3; } else { //both people have too much missing data so neither is used whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =0; whichVector[i+3]=0; } } for (int i = numTrios*4; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); boolean tooManyMissingInASegment = false; int totalMissing = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missing = 0; for (int j = 0; j < block_size[n]; j++){ byte theGeno = thisChrom.getGenotype(theBlock[segmentShift+j]); byte nextGeno = nextChrom.getGenotype(theBlock[segmentShift+j]); if(theGeno == 0 || nextGeno == 0) missing++; } segmentShift += block_size[n]; if (missing >= MISSINGLIMIT){ tooManyMissingInASegment = true; } totalMissing += missing; } //we want to use chromosomes without too many missing genotypes in a given //subsegment (first term) or without too many missing genotypes in the //whole block (second term) if (!tooManyMissingInASegment && totalMissing <= 1+theBlock.length/3){ whichVector[i-1] = 1; whichVector[i] = 1; } } //we only want to add an affected status every other chromosome, so we flip this boolean each time boolean addAff = true; for (int i = 0; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); if(whichVector[i] > 0) { thisHap = new byte[theBlock.length]; for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getMarker(theBlock[j]).getMinor(); byte theGeno = thisChrom.getGenotype(theBlock[j]); if (theGeno >= 5){ thisHap[j] = 'h'; } else { if (theGeno == a1){ thisHap[j] = '1'; }else if (theGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } if(whichVector[i] == 1) { inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(thisChrom.getAffected())); } } else if(whichVector[i] ==2) { inputHaploTrios.add(thisHap); if(addAff) { affTrios.add(new Integer(thisChrom.getAffected())); } }else if (whichVector[i] == 3){ inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(0)); } } if(addAff) { addAff = false; } else { addAff =true; } } } int trioCount = inputHaploTrios.size() / 4; inputHaploTrios.addAll(inputHaploSingletons); affTrios.addAll(affSingletons); byte[][] input_haplos = (byte[][])inputHaploTrios.toArray(new byte[0][0]); full_em_breakup(input_haplos, block_size, trioCount, affTrios); }
public void doEM(int[] theBlock) throws HaploViewException{ //break up large blocks if needed int[] block_size; if (theBlock.length < 9){ block_size = new int[1]; block_size[0] = theBlock.length; } else { //some base-8 arithmetic int ones = theBlock.length%8; int eights = (theBlock.length - ones)/8; if (ones == 0){ block_size = new int[eights]; for (int i = 0; i < eights; i++){ block_size[i]=8; } } else { block_size = new int[eights+1]; for (int i = 0; i < eights-1; i++){ block_size[i]=8; } block_size[eights-1] = (8+ones)/2; block_size[eights] = 8+ones-block_size[eights-1]; } } byte[] thisHap; Vector inputHaploSingletons = new Vector(); Vector inputHaploTrios = new Vector(); Vector affSingletons = new Vector(); Vector affTrios = new Vector(); //whichVector[i] stores a value which indicates which vector chromosome i's genotype should go in //1 indicates inputHaploSingletons (singletons), 2 indicates inputHaploTrios, //3 indicates a person from a broken trio who is treated as a singleton //0 indicates none (too much missing data) int[] whichVector = new int[chromosomes.size()]; for(int i=0;i<numTrios*4; i+=4) { Chromosome parentAFirst = (Chromosome) chromosomes.elementAt(i); Chromosome parentASecond = (Chromosome) chromosomes.elementAt(i+1); Chromosome parentBFirst = (Chromosome) chromosomes.elementAt(i+2); Chromosome parentBSecond = (Chromosome) chromosomes.elementAt(i+3); boolean tooManyMissingInASegmentA = false; boolean tooManyMissingInASegmentB = false; int totalMissingA = 0; int totalMissingB = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missingA = 0; int missingB = 0; for (int j = 0; j < block_size[n]; j++){ byte AFirstGeno = parentAFirst.getGenotype(theBlock[segmentShift+j]); byte ASecondGeno = parentASecond.getGenotype(theBlock[segmentShift+j]); byte BFirstGeno = parentBFirst.getGenotype(theBlock[segmentShift+j]); byte BSecondGeno = parentBSecond.getGenotype(theBlock[segmentShift+j]); if(AFirstGeno == 0 || ASecondGeno == 0) missingA++; if(BFirstGeno == 0 || BSecondGeno == 0) missingB++; } segmentShift += block_size[n]; if (missingA >= MISSINGLIMIT){ tooManyMissingInASegmentA = true; } if (missingB >= MISSINGLIMIT){ tooManyMissingInASegmentB = true; } totalMissingA += missingA; totalMissingB += missingB; } if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3 && !tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //both parents are good so all 4 chroms are added as a trio whichVector[i] = 2; whichVector[i+1] = 2; whichVector[i+2] = 2; whichVector[i+3] = 2; } else if(!tooManyMissingInASegmentA && totalMissingA <= 1+theBlock.length/3) { //first person good, so he's added as a singleton, other parent is dropped whichVector[i] = 3; whichVector[i+1] =3; whichVector[i+2] =0; whichVector[i+3]=0; } else if(!tooManyMissingInASegmentB && totalMissingB <= 1+theBlock.length/3) { //second person good, so he's added as a singleton, other parent is dropped whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =3; whichVector[i+3]=3; } else { //both people have too much missing data so neither is used whichVector[i] = 0; whichVector[i+1] =0; whichVector[i+2] =0; whichVector[i+3]=0; } } for (int i = numTrios*4; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); boolean tooManyMissingInASegment = false; int totalMissing = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missing = 0; for (int j = 0; j < block_size[n]; j++){ byte theGeno = thisChrom.getGenotype(theBlock[segmentShift+j]); byte nextGeno = nextChrom.getGenotype(theBlock[segmentShift+j]); if(theGeno == 0 || nextGeno == 0) missing++; } segmentShift += block_size[n]; if (missing >= MISSINGLIMIT){ tooManyMissingInASegment = true; } totalMissing += missing; } //we want to use chromosomes without too many missing genotypes in a given //subsegment (first term) or without too many missing genotypes in the //whole block (second term) if (!tooManyMissingInASegment && totalMissing <= 1+theBlock.length/3){ whichVector[i-1] = 1; whichVector[i] = 1; } } //we only want to add an affected status every other chromosome, so we flip this boolean each time boolean addAff = true; for (int i = 0; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); if(whichVector[i] > 0) { thisHap = new byte[theBlock.length]; for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getMarker(theBlock[j]).getMinor(); byte theGeno = thisChrom.getGenotype(theBlock[j]); if (theGeno >= 5){ thisHap[j] = 'h'; } else { if (theGeno == a1){ thisHap[j] = '1'; }else if (theGeno == a2){ thisHap[j] = '2'; }else{ throw new HaploViewException("Marker with > 2 alleles: " + Chromosome.getMarker(theBlock[j]).getName()); } } } if(whichVector[i] == 1) { inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(thisChrom.getAffected())); } } else if(whichVector[i] ==2) { inputHaploTrios.add(thisHap); if(addAff) { affTrios.add(new Integer(thisChrom.getAffected())); } }else if (whichVector[i] == 3){ inputHaploSingletons.add(thisHap); if(addAff) { affSingletons.add(new Integer(0)); } } if(addAff) { addAff = false; } else { addAff =true; } } } int trioCount = inputHaploTrios.size() / 4; inputHaploTrios.addAll(inputHaploSingletons); affTrios.addAll(affSingletons); byte[][] input_haplos = (byte[][])inputHaploTrios.toArray(new byte[0][0]); full_em_breakup(input_haplos, block_size, trioCount, affTrios); }
1,109,092
public void redoRatings(){ try{ Vector result = pedfile.check(); for (int i = 0; i < table.getRowCount(); i++){ MarkerResult cur = (MarkerResult)result.get(i); if (cur.getRating() > 0){ table.setValueAt(new Boolean(true),i,STATUS_COL); }else{ table.setValueAt(new Boolean(false),i,STATUS_COL); } } changed = true; }catch (Exception e){ e.printStackTrace(); } }
public void redoRatings(){ try{ Vector result = pedfile.check(); for (int i = 0; i < table.getRowCount(); i++){ MarkerResult cur = (MarkerResult)result.get(i); int curRating = cur.getRating(); if (curRating > 0){ table.setValueAt(new Boolean(true),i,STATUS_COL); }else{ table.setValueAt(new Boolean(false),i,STATUS_COL); } } changed = true; }catch (Exception e){ e.printStackTrace(); } }
1,109,093
EM(Vector chromosomes, int numTrios, Vector extraInds){ //we need to add extra copies of haploid chromosomes so we add a second copy this.chromosomes = new Vector(); for(int i=0;i<extraInds.size();i++){ this.chromosomes.add(extraInds.elementAt(i)); if(((Chromosome)this.chromosomes.lastElement()).isHaploid()){ this.chromosomes.add(extraInds.elementAt(i)); } } extraTrioCount = this.chromosomes.size()/4; for(int i=0;i<chromosomes.size();i++) { this.chromosomes.add(chromosomes.elementAt(i)); if(((Chromosome)this.chromosomes.lastElement()).isHaploid()){ this.chromosomes.add(chromosomes.elementAt(i)); } } this.numTrios = numTrios + extraTrioCount; }
EM(Vector chromosomes, int numTrios, Vector extraInds){ //we need to add extra copies of haploid chromosomes so we add a second copy this.chromosomes = new Vector(); for(int i=0;i<extraInds.size();i++){ this.chromosomes.add(extraInds.elementAt(i)); if(((Chromosome)this.chromosomes.lastElement()).isHaploid()){ this.chromosomes.add(extraInds.elementAt(i)); } } extraTrioCount = this.chromosomes.size()/4; for(int i=0;i<chromosomes.size();i++) { this.chromosomes.add(chromosomes.elementAt(i)); if(((Chromosome)this.chromosomes.lastElement()).isHaploid()){ this.chromosomes.add(chromosomes.elementAt(i)); } } this.numTrios = numTrios + extraTrioCount; }
1,109,094
public synchronized void setupDialog() { if (d != null) return; d = new JDialog(ArchitectFrame.getMainInstance(), "Export ETL Transactions to PL Repository"); // set export defaults if necessary if (plexp.getFolderName() == null || plexp.getFolderName().trim().length() == 0) { plexp.setFolderName(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_FOLDER")); } if (plexp.getJobId() == null || plexp.getJobId().trim().length() == 0) { plexp.setJobId(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_JOB")); } JPanel plp = new JPanel(new BorderLayout(12,12)); plp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final PLExportPanel plPanel = new PLExportPanel(); plPanel.setPLExport(plexp); plp.add(plPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); if (plexp.getPlDBCS() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getPlUsername().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader User Name.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) return; } plexp.export(playpen.getDatabase()); if (plPanel.isSelectedRunPLEngine()) { logger.debug("Running PL Engine"); File plIni = new File(architectFrame.getUserSettings().getETLUserSettings().getPlDotIniPath()); File plDir = plIni.getParentFile(); File engineExe = new File(plDir, plPanel.getPLConnectionSpec().getEngineExeutableName()); StringBuffer commandLine = new StringBuffer(1000); commandLine.append(engineExe.getPath()); commandLine.append(" USER_PROMPT=N"); commandLine.append(" JOB=").append(plexp.getJobId()); commandLine.append(" USER=").append(plPanel.getPLConnectionSpec().getEngineConnectString()); 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" ); logger.debug(commandLine.toString()); try { Process proc = Runtime.getRuntime().exec(commandLine.toString()); JDialog d = new JDialog(architectFrame, "Power*Loader Engine"); d.setContentPane(new EngineExecPanel(commandLine.toString(), proc)); d.pack(); d.setLocationRelativeTo(plPanel); d.setVisible(true); } catch (IOException ie){ JOptionPane.showMessageDialog(playpen, "Unexpected Exception running Engine:\n"+ie); logger.error(ie); } } } catch (PLSecurityException ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+ex.getMessage()); logger.error("Got exception while exporting Trans", ex); } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans", arex); } finally { d.setVisible(false); } } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); plp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(plp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); }
public synchronized void setupDialog() { if (d != null) return; d = new JDialog(ArchitectFrame.getMainInstance(), "Export ETL Transactions to PL Repository"); // set export defaults if necessary if (plexp.getFolderName() == null || plexp.getFolderName().trim().length() == 0) { plexp.setFolderName(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_FOLDER")); } if (plexp.getJobId() == null || plexp.getJobId().trim().length() == 0) { plexp.setJobId(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_JOB")); } JPanel plp = new JPanel(new BorderLayout(12,12)); plp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final PLExportPanel plPanel = new PLExportPanel(); plPanel.setPLExport(plexp); plp.add(plPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); if (plexp.getPlDBCS() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getPlUsername().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader User Name.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) return; } plexp.export(playpen.getDatabase()); if (plPanel.isSelectedRunPLEngine()) { logger.debug("Running PL Engine"); File plIni = new File(architectFrame.getUserSettings().getETLUserSettings().getPlDotIniPath()); File plDir = plIni.getParentFile(); File engineExe = new File(plDir, plPanel.getPLConnectionSpec().getEngineExeutableName()); StringBuffer commandLine = new StringBuffer(1000); commandLine.append(engineExe.getPath()); commandLine.append(" USER_PROMPT=N"); commandLine.append(" JOB=").append(plexp.getJobId()); commandLine.append(" USER=").append(plPanel.getPLConnectionSpec().getEngineConnectString()); 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" ); logger.debug(commandLine.toString()); try { Process proc = Runtime.getRuntime().exec(commandLine.toString()); JDialog d = new JDialog(architectFrame, "Power*Loader Engine"); d.setContentPane(new EngineExecPanel(commandLine.toString(), proc)); d.pack(); d.setLocationRelativeTo(plPanel); d.setVisible(true); } catch (IOException ie){ JOptionPane.showMessageDialog(playpen, "Unexpected Exception running Engine:\n"+ie); logger.error(ie); } } } catch (PLSecurityException ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+ex.getMessage()); logger.error("Got exception while exporting Trans", ex); } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans", arex); } finally { d.setVisible(false); } } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); plp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(plp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); }
1,109,096
public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); if (plexp.getPlDBCS() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getPlUsername().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader User Name.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) return; } plexp.export(playpen.getDatabase()); if (plPanel.isSelectedRunPLEngine()) { logger.debug("Running PL Engine"); File plIni = new File(architectFrame.getUserSettings().getETLUserSettings().getPlDotIniPath()); File plDir = plIni.getParentFile(); File engineExe = new File(plDir, plPanel.getPLConnectionSpec().getEngineExeutableName()); StringBuffer commandLine = new StringBuffer(1000); commandLine.append(engineExe.getPath()); commandLine.append(" USER_PROMPT=N"); commandLine.append(" JOB=").append(plexp.getJobId()); commandLine.append(" USER=").append(plPanel.getPLConnectionSpec().getEngineConnectString()); 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" ); logger.debug(commandLine.toString()); try { Process proc = Runtime.getRuntime().exec(commandLine.toString()); JDialog d = new JDialog(architectFrame, "Power*Loader Engine"); d.setContentPane(new EngineExecPanel(commandLine.toString(), proc)); d.pack(); d.setLocationRelativeTo(plPanel); d.setVisible(true); } catch (IOException ie){ JOptionPane.showMessageDialog(playpen, "Unexpected Exception running Engine:\n"+ie); logger.error(ie); } } } catch (PLSecurityException ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+ex.getMessage()); logger.error("Got exception while exporting Trans", ex); } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans", arex); } finally { d.setVisible(false); } }
public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); if (plexp.getPlDBCS() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getPlUsername().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader User Name.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) return; } plexp.export(playpen.getDatabase()); if (plPanel.isSelectedRunPLEngine()) { logger.debug("Running PL Engine"); File plIni = new File(architectFrame.getUserSettings().getETLUserSettings().getPlDotIniPath()); File plDir = plIni.getParentFile(); File engineExe = new File(plDir, plPanel.getPLConnectionSpec().getEngineExeutableName()); StringBuffer commandLine = new StringBuffer(1000); commandLine.append(engineExe.getPath()); commandLine.append(" USER_PROMPT=N"); commandLine.append(" JOB=").append(plexp.getJobId()); commandLine.append(" USER=").append(plPanel.getPLConnectionSpec().getEngineConnectString()); 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" ); logger.debug(commandLine.toString()); try { Process proc = Runtime.getRuntime().exec(commandLine.toString()); JDialog d = new JDialog(architectFrame, "Power*Loader Engine"); d.setContentPane(new EngineExecPanel(commandLine.toString(), proc)); d.pack(); d.setLocationRelativeTo(plPanel); d.setVisible(true); } catch (IOException ie){ JOptionPane.showMessageDialog(playpen, "Unexpected Exception running Engine:\n"+ie); logger.error(ie); } } } catch (PLSecurityException ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+ex.getMessage()); logger.error("Got exception while exporting Trans", ex); } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame, "Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans", arex); } finally { d.setVisible(false); } }
1,109,097
public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); }
public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); }
1,109,098
public PairwiseLinkage computeDPrime(int pos1, int pos2){ int doublehet = 0; int[][] twoMarkerHaplos = new int[3][3]; for (int i = 0; i < twoMarkerHaplos.length; i++){ for (int j = 0; j < twoMarkerHaplos[i].length; j++){ twoMarkerHaplos[i][j] = 0; } } //check for non-polymorphic markers if (Chromosome.getUnfilteredMarker(pos1).getMAF() == 0 || Chromosome.getUnfilteredMarker(pos2).getMAF() == 0){ return null; } int[] marker1num = new int[5]; int[] marker2num = new int[5]; marker1num[0]=0; marker1num[Chromosome.getUnfilteredMarker(pos1).getMajor()]=1; marker1num[Chromosome.getUnfilteredMarker(pos1).getMinor()]=2; marker2num[0]=0; marker2num[Chromosome.getUnfilteredMarker(pos2).getMajor()]=1; marker2num[Chromosome.getUnfilteredMarker(pos2).getMinor()]=2; byte a1,a2,b1,b2; //iterate through all chromosomes in dataset for (int i = 0; i < chromosomes.size(); i++){ //System.out.println(i + " " + pos1 + " " + pos2); //assign alleles for each of a pair of chromosomes at a marker to four variables a1 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos1]; a2 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos2]; b1 = ((Chromosome) chromosomes.elementAt(++i)).genotypes[pos1]; b2 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos2]; if (a1 == 0 || a2 == 0 || b1 == 0 || b2 == 0){ //skip missing data } else if (((a1 >= 5 || b1 >= 5) && (a2 >= 5 || b2 >= 5)) || (a1 >= 5 && !(a2 == b2)) || (a2 >= 5 && !(a1 == b1))){ doublehet++; //find doublehets and resolved haplotypes } else if (a1 >= 5 || b1 >= 5){ twoMarkerHaplos[1][marker2num[a2]]++; twoMarkerHaplos[2][marker2num[a2]]++; } else if (a2 >= 5 || b2 >= 5){ twoMarkerHaplos[marker1num[a1]][1]++; twoMarkerHaplos[marker1num[a1]][2]++; } else { twoMarkerHaplos[marker1num[a1]][marker2num[a2]]++; twoMarkerHaplos[marker1num[b1]][marker2num[b2]]++; } } //another monomorphic marker check int r1, r2, c1, c2; r1 = twoMarkerHaplos[1][1] + twoMarkerHaplos[1][2]; r2 = twoMarkerHaplos[2][1] + twoMarkerHaplos[2][2]; c1 = twoMarkerHaplos[1][1] + twoMarkerHaplos[2][1]; c2 = twoMarkerHaplos[1][2] + twoMarkerHaplos[2][2]; if ( (r1==0 || r2==0 || c1==0 || c2==0) && doublehet == 0){ return new PairwiseLinkage(1,0,0,0,0,new double[0]); } //compute D Prime for this pair of markers. //return is a tab delimited string of d', lod, r^2, CI(low), CI(high) int i,count; //int j,k,itmp; int low_i = 0; int high_i = 0; double loglike, oldloglike;// meand, mean2d, sd; double tmp;//g,h,m,tmp,r; double num, denom1, denom2, denom, dprime;//, real_dprime; double pA1, pB1, pA2, pB2, loglike1, loglike0, rsq; double tmpAA, tmpAB, tmpBA, tmpBB, dpr;// tmp2AA, tmp2AB, tmp2BA, tmp2BB; double total_prob, sum_prob; double lsurface[] = new double[101]; /* store arguments in externals and compute allele frequencies */ known[AA]=twoMarkerHaplos[1][1]; known[AB]=twoMarkerHaplos[1][2]; known[BA]=twoMarkerHaplos[2][1]; known[BB]=twoMarkerHaplos[2][2]; unknownDH=doublehet; total_chroms= (int)(known[AA]+known[AB]+known[BA]+known[BB]+(2*unknownDH)); pA1 = (known[AA]+known[AB]+unknownDH) / (double) total_chroms; pB1 = 1.0-pA1; pA2 = (known[AA]+known[BA]+unknownDH) / (double) total_chroms; pB2 = 1.0-pA2; const_prob = 0.1; /* set initial conditions */ if (const_prob < 0.00) { probHaps[AA]=pA1*pA2; probHaps[AB]=pA1*pB2; probHaps[BA]=pB1*pA2; probHaps[BB]=pB1*pB2; } else { probHaps[AA]=const_prob; probHaps[AB]=const_prob; probHaps[BA]=const_prob; probHaps[BB]=const_prob;; /* so that the first count step will produce an initial estimate without inferences (this should be closer and therefore speedier than assuming they are all at equal frequency) */ count_haps(0); estimate_p(); } /* now we have an initial reasonable guess at p we can start the EM - let the fun begin */ const_prob=0.0; count=1; loglike=-999999999.0; do { oldloglike=loglike; count_haps(count); loglike = (known[AA]*Math.log(probHaps[AA]) + known[AB]*Math.log(probHaps[AB]) + known[BA]*Math.log(probHaps[BA]) + known[BB]*Math.log(probHaps[BB]))/LN10 + ((double)unknownDH*Math.log(probHaps[AA]*probHaps[BB] + probHaps[AB]*probHaps[BA]))/LN10; if (Math.abs(loglike-oldloglike) < TOLERANCE) break; estimate_p(); count++; } while(count < 1000); /* in reality I've never seen it need more than 10 or so iterations to converge so this is really here just to keep it from running off into eternity */ loglike1 = (known[AA]*Math.log(probHaps[AA]) + known[AB]*Math.log(probHaps[AB]) + known[BA]*Math.log(probHaps[BA]) + known[BB]*Math.log(probHaps[BB]) + (double)unknownDH*Math.log(probHaps[AA]*probHaps[BB] + probHaps[AB]*probHaps[BA]))/LN10; loglike0 = (known[AA]*Math.log(pA1*pA2) + known[AB]*Math.log(pA1*pB2) + known[BA]*Math.log(pB1*pA2) + known[BB]*Math.log(pB1*pB2) + (double)unknownDH*Math.log(2*pA1*pA2*pB1*pB2))/LN10; num = probHaps[AA]*probHaps[BB] - probHaps[AB]*probHaps[BA]; if (num < 0) { /* flip matrix so we get the positive D' */ /* flip AA with AB and BA with BB */ tmp=probHaps[AA]; probHaps[AA]=probHaps[AB]; probHaps[AB]=tmp; tmp=probHaps[BB]; probHaps[BB]=probHaps[BA]; probHaps[BA]=tmp; /* flip frequency of second allele */ //done in this slightly asinine way because of a compiler bugz0r in the dec-alpha version of java //which causes it to try to parallelize the swapping operations and mis-schedules them pA2 = pA2 + pB2; pB2 = pA2 - pB2; pA2 = pA2 - pB2; //pA2=pB2;pB2=temp; /* flip counts in the same fashion as p's */ tmp=numHaps[AA]; numHaps[AA]=numHaps[AB]; numHaps[AB]=tmp; tmp=numHaps[BB]; numHaps[BB]=numHaps[BA]; numHaps[BA]=tmp; /* num has now undergone a sign change */ num = probHaps[AA]*probHaps[BB] - probHaps[AB]*probHaps[BA]; /* flip known array for likelihood computation */ tmp=known[AA]; known[AA]=known[AB]; known[AB]=tmp; tmp=known[BB]; known[BB]=known[BA]; known[BA]=tmp; } denom1 = (probHaps[AA]+probHaps[BA])*(probHaps[BA]+probHaps[BB]); denom2 = (probHaps[AA]+probHaps[AB])*(probHaps[AB]+probHaps[BB]); if (denom1 < denom2) { denom = denom1; } else { denom = denom2; } dprime = num/denom; /* add computation of r^2 = (D^2)/p(1-p)q(1-q) */ rsq = num*num/(pA1*pB1*pA2*pB2); //real_dprime=dprime; for (i=0; i<=100; i++) { dpr = (double)i*0.01; tmpAA = dpr*denom + pA1*pA2; tmpAB = pA1-tmpAA; tmpBA = pA2-tmpAA; tmpBB = pB1-tmpBA; if (i==100) { /* one value will be 0 */ if (tmpAA < 1e-10) tmpAA=1e-10; if (tmpAB < 1e-10) tmpAB=1e-10; if (tmpBA < 1e-10) tmpBA=1e-10; if (tmpBB < 1e-10) tmpBB=1e-10; } lsurface[i] = (known[AA]*Math.log(tmpAA) + known[AB]*Math.log(tmpAB) + known[BA]*Math.log(tmpBA) + known[BB]*Math.log(tmpBB) + (double)unknownDH*Math.log(tmpAA*tmpBB + tmpAB*tmpBA))/LN10; } /* Confidence bounds #2 - used in Gabriel et al (2002) - translate into posterior dist of D' - assumes a flat prior dist. of D' - someday we may be able to make this even more clever by adjusting given the distribution of observed D' values for any given distance after some large scale studies are complete */ total_prob=sum_prob=0.0; for (i=0; i<=100; i++) { lsurface[i] -= loglike1; lsurface[i] = Math.pow(10.0,lsurface[i]); total_prob += lsurface[i]; } for (i=0; i<=100; i++) { sum_prob += lsurface[i]; if (sum_prob > 0.05*total_prob && sum_prob-lsurface[i] < 0.05*total_prob) { low_i = i-1; break; } } sum_prob=0.0; for (i=100; i>=0; i--) { sum_prob += lsurface[i]; if (sum_prob > 0.05*total_prob && sum_prob-lsurface[i] < 0.05*total_prob) { high_i = i+1; break; } } if (high_i > 100){ high_i = 100; } double[] freqarray = {probHaps[AA], probHaps[AB], probHaps[BB], probHaps[BA]}; return new PairwiseLinkage(Util.roundDouble(dprime,3), Util.roundDouble((loglike1-loglike0),2), Util.roundDouble(rsq,3), ((double)low_i/100.0), ((double)high_i/100.0), freqarray); }
public PairwiseLinkage computeDPrime(int pos1, int pos2){ int doublehet = 0; int[][] twoMarkerHaplos = new int[3][3]; for (int i = 0; i < twoMarkerHaplos.length; i++){ for (int j = 0; j < twoMarkerHaplos[i].length; j++){ twoMarkerHaplos[i][j] = 0; } } //check for non-polymorphic markers if (Chromosome.getUnfilteredMarker(pos1).getMAF() == 0 || Chromosome.getUnfilteredMarker(pos2).getMAF() == 0){ return null; } int[] marker1num = new int[5]; int[] marker2num = new int[5]; marker1num[0]=0; marker1num[Chromosome.getUnfilteredMarker(pos1).getMajor()]=1; marker1num[Chromosome.getUnfilteredMarker(pos1).getMinor()]=2; marker2num[0]=0; marker2num[Chromosome.getUnfilteredMarker(pos2).getMajor()]=1; marker2num[Chromosome.getUnfilteredMarker(pos2).getMinor()]=2; byte a1,a2,b1,b2; //iterate through all chromosomes in dataset for (int i = 0; i < chromosomes.size(); i++){ //System.out.println(i + " " + pos1 + " " + pos2); //assign alleles for each of a pair of chromosomes at a marker to four variables a1 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos1]; a2 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos2]; b1 = ((Chromosome) chromosomes.elementAt(++i)).genotypes[pos1]; b2 = ((Chromosome) chromosomes.elementAt(i)).genotypes[pos2]; if (a1 == 0 || a2 == 0 || b1 == 0 || b2 == 0){ //skip missing data } else if (((a1 >= 5 || b1 >= 5) && (a2 >= 5 || b2 >= 5)) || (a1 >= 5 && !(a2 == b2)) || (a2 >= 5 && !(a1 == b1))){ doublehet++; //find doublehets and resolved haplotypes } else if (a1 >= 5 || b1 >= 5){ twoMarkerHaplos[1][marker2num[a2]]++; twoMarkerHaplos[2][marker2num[a2]]++; } else if (a2 >= 5 || b2 >= 5){ twoMarkerHaplos[marker1num[a1]][1]++; twoMarkerHaplos[marker1num[a1]][2]++; } else { twoMarkerHaplos[marker1num[a1]][marker2num[a2]]++; twoMarkerHaplos[marker1num[b1]][marker2num[b2]]++; } } //another monomorphic marker check int r1, r2, c1, c2; r1 = twoMarkerHaplos[1][1] + twoMarkerHaplos[1][2]; r2 = twoMarkerHaplos[2][1] + twoMarkerHaplos[2][2]; c1 = twoMarkerHaplos[1][1] + twoMarkerHaplos[2][1]; c2 = twoMarkerHaplos[1][2] + twoMarkerHaplos[2][2]; if ( (r1==0 || r2==0 || c1==0 || c2==0) && doublehet == 0){ return new PairwiseLinkage(1,0,0,0,0,new double[0]); } //compute D Prime for this pair of markers. //return is a tab delimited string of d', lod, r^2, CI(low), CI(high) int i,count; //int j,k,itmp; int low_i = 0; int high_i = 0; double loglike, oldloglike;// meand, mean2d, sd; double tmp;//g,h,m,tmp,r; double num, denom1, denom2, denom, dprime;//, real_dprime; double pA1, pB1, pA2, pB2, loglike1, loglike0, rsq; double tmpAA, tmpAB, tmpBA, tmpBB, dpr;// tmp2AA, tmp2AB, tmp2BA, tmp2BB; double total_prob, sum_prob; double lsurface[] = new double[101]; /* store arguments in externals and compute allele frequencies */ known[AA]=twoMarkerHaplos[1][1]; known[AB]=twoMarkerHaplos[1][2]; known[BA]=twoMarkerHaplos[2][1]; known[BB]=twoMarkerHaplos[2][2]; unknownDH=doublehet; total_chroms= (int)(known[AA]+known[AB]+known[BA]+known[BB]+(2*unknownDH)); pA1 = (known[AA]+known[AB]+unknownDH) / (double) total_chroms; pB1 = 1.0-pA1; pA2 = (known[AA]+known[BA]+unknownDH) / (double) total_chroms; pB2 = 1.0-pA2; const_prob = 0.1; /* set initial conditions */ if (const_prob < 0.00) { probHaps[AA]=pA1*pA2; probHaps[AB]=pA1*pB2; probHaps[BA]=pB1*pA2; probHaps[BB]=pB1*pB2; } else { probHaps[AA]=const_prob; probHaps[AB]=const_prob; probHaps[BA]=const_prob; probHaps[BB]=const_prob;; /* so that the first count step will produce an initial estimate without inferences (this should be closer and therefore speedier than assuming they are all at equal frequency) */ count_haps(0); estimate_p(); } /* now we have an initial reasonable guess at p we can start the EM - let the fun begin */ const_prob=0.0; count=1; loglike=-999999999.0; do { oldloglike=loglike; count_haps(count); loglike = (known[AA]*Math.log(probHaps[AA]) + known[AB]*Math.log(probHaps[AB]) + known[BA]*Math.log(probHaps[BA]) + known[BB]*Math.log(probHaps[BB]))/LN10 + ((double)unknownDH*Math.log(probHaps[AA]*probHaps[BB] + probHaps[AB]*probHaps[BA]))/LN10; if (Math.abs(loglike-oldloglike) < TOLERANCE) break; estimate_p(); count++; } while(count < 1000); /* in reality I've never seen it need more than 10 or so iterations to converge so this is really here just to keep it from running off into eternity */ loglike1 = (known[AA]*Math.log(probHaps[AA]) + known[AB]*Math.log(probHaps[AB]) + known[BA]*Math.log(probHaps[BA]) + known[BB]*Math.log(probHaps[BB]) + (double)unknownDH*Math.log(probHaps[AA]*probHaps[BB] + probHaps[AB]*probHaps[BA]))/LN10; loglike0 = (known[AA]*Math.log(pA1*pA2) + known[AB]*Math.log(pA1*pB2) + known[BA]*Math.log(pB1*pA2) + known[BB]*Math.log(pB1*pB2) + (double)unknownDH*Math.log(2*pA1*pA2*pB1*pB2))/LN10; num = probHaps[AA]*probHaps[BB] - probHaps[AB]*probHaps[BA]; if (num < 0) { /* flip matrix so we get the positive D' */ /* flip AA with AB and BA with BB */ tmp=probHaps[AA]; probHaps[AA]=probHaps[AB]; probHaps[AB]=tmp; tmp=probHaps[BB]; probHaps[BB]=probHaps[BA]; probHaps[BA]=tmp; /* flip frequency of second allele */ //done in this slightly asinine way because of a compiler bugz0r in the dec-alpha version of java //which causes it to try to parallelize the swapping operations and mis-schedules them pA2 = pA2 + pB2; pB2 = pA2 - pB2; pA2 = pA2 - pB2; //pA2=pB2;pB2=temp; /* flip counts in the same fashion as p's */ tmp=numHaps[AA]; numHaps[AA]=numHaps[AB]; numHaps[AB]=tmp; tmp=numHaps[BB]; numHaps[BB]=numHaps[BA]; numHaps[BA]=tmp; /* num has now undergone a sign change */ num = probHaps[AA]*probHaps[BB] - probHaps[AB]*probHaps[BA]; /* flip known array for likelihood computation */ tmp=known[AA]; known[AA]=known[AB]; known[AB]=tmp; tmp=known[BB]; known[BB]=known[BA]; known[BA]=tmp; } denom1 = (probHaps[AA]+probHaps[BA])*(probHaps[BA]+probHaps[BB]); denom2 = (probHaps[AA]+probHaps[AB])*(probHaps[AB]+probHaps[BB]); if (denom1 < denom2) { denom = denom1; } else { denom = denom2; } dprime = num/denom; /* add computation of r^2 = (D^2)/p(1-p)q(1-q) */ rsq = num*num/(pA1*pB1*pA2*pB2); //real_dprime=dprime; for (i=0; i<=100; i++) { dpr = (double)i*0.01; tmpAA = dpr*denom + pA1*pA2; tmpAB = pA1-tmpAA; tmpBA = pA2-tmpAA; tmpBB = pB1-tmpBA; if (i==100) { /* one value will be 0 */ if (tmpAA < 1e-10) tmpAA=1e-10; if (tmpAB < 1e-10) tmpAB=1e-10; if (tmpBA < 1e-10) tmpBA=1e-10; if (tmpBB < 1e-10) tmpBB=1e-10; } lsurface[i] = (known[AA]*Math.log(tmpAA) + known[AB]*Math.log(tmpAB) + known[BA]*Math.log(tmpBA) + known[BB]*Math.log(tmpBB) + (double)unknownDH*Math.log(tmpAA*tmpBB + tmpAB*tmpBA))/LN10; } /* Confidence bounds #2 - used in Gabriel et al (2002) - translate into posterior dist of D' - assumes a flat prior dist. of D' - someday we may be able to make this even more clever by adjusting given the distribution of observed D' values for any given distance after some large scale studies are complete */ total_prob=sum_prob=0.0; for (i=0; i<=100; i++) { lsurface[i] -= loglike1; lsurface[i] = Math.pow(10.0,lsurface[i]); total_prob += lsurface[i]; } for (i=0; i<=100; i++) { sum_prob += lsurface[i]; if (sum_prob > 0.05*total_prob && sum_prob-lsurface[i] < 0.05*total_prob) { low_i = i-1; break; } } sum_prob=0.0; for (i=100; i>=0; i--) { sum_prob += lsurface[i]; if (sum_prob > 0.05*total_prob && sum_prob-lsurface[i] < 0.05*total_prob) { high_i = i+1; break; } } if (high_i > 100){ high_i = 100; } double[] freqarray = {probHaps[AA], probHaps[AB], probHaps[BB], probHaps[BA]}; return new PairwiseLinkage(Util.roundDouble(dprime,3), Util.roundDouble((loglike1-loglike0),2), Util.roundDouble(rsq,3), ((double)low_i/100.0), ((double)high_i/100.0), freqarray); }
1,109,099
public String getToolTipText(MouseEvent e) { return contentPane.getToolTipText(e); }
public String getToolTipText(MouseEvent e) { Point zp = unzoomPoint(e.getPoint()); MouseEvent zoomedEvent = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), zp.x, zp.y, e.getClickCount(), e.isPopupTrigger(), e.getButton()); return contentPane.getToolTipText(zoomedEvent); }
1,109,102
public void testSourceDropDownsWithOnlyCatalog() { ArchitectDataSource ds = new ArchitectDataSource(); ds.setDisplayName("testSourceDropDownsWithOnlyCatalog"); ds.setDriverClass("ca.sqlpower.architect.MockJDBCDriver"); ds.setUser("fake"); ds.setPass("fake"); //this creates a mock jdbc database with only catalogs ds.setUrl("jdbc:mock:" + "dbmd.catalogTerm=Catalog" + "&catalogs=cat1,cat2,cat3" + "&tables.cat1=tab1" + "&tables.cat2=tab2" + "&tables.cat3=tab3"); sourcePhysicalRadio.setSelected(true); ArchitectFrame.getMainInstance().getUserSettings().getPlDotIni().addDataSource(ds); sourceDatabaseDropdown.setSelectedItem(ds); flushAWT(); assertFalse(sourceSchemaDropdown.isEnabled()); assertTrue(sourceCatalogDropdown.isEnabled()); }
public void testSourceDropDownsWithOnlyCatalog() { ArchitectDataSource ds = new ArchitectDataSource(); ds.setDisplayName("testSourceDropDownsWithOnlyCatalog"); ds.setDriverClass("ca.sqlpower.architect.MockJDBCDriver"); ds.setUser("fake"); ds.setPass("fake"); //this creates a mock jdbc database with only catalogs ds.setUrl("jdbc:mock:" + "dbmd.catalogTerm=Catalog" + "&catalogs=cat1,cat2,cat3" + "&tables.cat1=tab1" + "&tables.cat2=tab2" + "&tables.cat3=tab3"); sourcePhysicalRadio.setSelected(true); if (plDotIni.getDataSource(ds.getName()) != null) { plDotIni.removeDataSource(ds); } plDotIni.addDataSource(ds); sourceDatabaseDropdown.setSelectedItem(ds); flushAWT(); assertFalse(sourceSchemaDropdown.isEnabled()); assertTrue(sourceCatalogDropdown.isEnabled()); }
1,109,103
public void testSourceDropDownsWithSchemaAndCatalog() { ArchitectDataSource ds = new ArchitectDataSource(); ds.setDisplayName("testSourceDropDownsWithSchemaAndCatalog"); ds.setDriverClass("ca.sqlpower.architect.MockJDBCDriver"); ds.setUser("fake"); ds.setPass("fake"); //this creates a mock jdbc database with catalogs and schemas ds.setUrl("jdbc:mock:dbmd.catalogTerm=Catalog&dbmd.schemaTerm=Schema&catalogs=cow_catalog&schemas.cow_catalog=moo_schema,quack_schema&tables.cow_catalog.moo_schema=braaaap,pffft&tables.cow_catalog.quack_schema=duck,goose"); sourcePhysicalRadio.setSelected(true); ArchitectFrame.getMainInstance().getUserSettings().getPlDotIni().addDataSource(ds); sourceDatabaseDropdown.setSelectedItem(ds); flushAWT(); assertTrue(sourceCatalogDropdown.isEnabled()); assertTrue(sourceSchemaDropdown.isEnabled()); }
public void testSourceDropDownsWithSchemaAndCatalog() { ArchitectDataSource ds = new ArchitectDataSource(); ds.setDisplayName("testSourceDropDownsWithSchemaAndCatalog"); ds.setDriverClass("ca.sqlpower.architect.MockJDBCDriver"); ds.setUser("fake"); ds.setPass("fake"); //this creates a mock jdbc database with catalogs and schemas ds.setUrl("jdbc:mock:dbmd.catalogTerm=Catalog&dbmd.schemaTerm=Schema&catalogs=cow_catalog&schemas.cow_catalog=moo_schema,quack_schema&tables.cow_catalog.moo_schema=braaaap,pffft&tables.cow_catalog.quack_schema=duck,goose"); sourcePhysicalRadio.setSelected(true); if (plDotIni.getDataSource(ds.getName()) != null) { plDotIni.removeDataSource(ds); } plDotIni.addDataSource(ds); sourceDatabaseDropdown.setSelectedItem(ds); flushAWT(); assertTrue(sourceCatalogDropdown.isEnabled()); assertTrue(sourceSchemaDropdown.isEnabled()); }
1,109,104
public void createDatabase( String user, String passwd ) { // Get the database schema XML file InputStream schemaIS = getClass().getClassLoader().getResourceAsStream( "photovault_schema.xml" ); Database dbModel = new DatabaseIO().read( new InputStreamReader( schemaIS ) ); // Create the datasource for accessing this database String driverName = "com.mysql.jdbc.Driver"; String dbUrl = "jdbc:mysql://" + getDbHost() + "/" + getDbName(); DataSource ds = null; if ( instanceType == TYPE_EMBEDDED ) { if ( !embeddedDirectory.exists() ) { embeddedDirectory.mkdirs(); } File derbyDir = new File( embeddedDirectory, "derby" ); File photoDir = new File( embeddedDirectory, "photos"); Volume vol = new Volume( "photos", photoDir.getAbsolutePath() ); addVolume( vol ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); driverName = "org.apache.derby.jdbc.EmbeddedDriver"; dbUrl = "jdbc:derby:photovault;create=true"; EmbeddedDataSource derbyDs = new EmbeddedDataSource(); derbyDs.setDatabaseName( "photovault" ); derbyDs.setCreateDatabase( "create" ); ds = derbyDs; } else { MysqlDataSource mysqlDs = new MysqlDataSource(); mysqlDs.setURL( dbUrl ); mysqlDs.setUser( user ); mysqlDs.setPassword( passwd ); ds = mysqlDs; } Platform platform = PlatformFactory.createNewPlatformInstance( ds ); /* * Do not use delimiters for the database object names in SQL statements. * This is to avoid case sensitivity problems with SQL92 compliant * databases like Derby - non-delimited identifiers are interpreted as case * insensitive. * * I am not sure if this is the correct way to solve the issue, however, * I am not willing to make a big change of schema definitions either. */ platform.getPlatformInfo().setDelimiterToken( "" ); platform.setUsername( user ); platform.setPassword( passwd ); platform.createTables( dbModel, true, true ); // Insert the seed data to database DataToDatabaseSink sink = new DataToDatabaseSink( platform, dbModel ); DataReader reader = new DataReader(); reader.setModel( dbModel ); reader.setSink( sink ); InputStream seedDataStream = this.getClass().getClassLoader().getResourceAsStream( "photovault_seed_data.xml" ); try { reader.parse( seedDataStream ); } catch (SAXException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } // Create the database // TODO: Since the seed has only 48 significant bits this id is not really an // 128-bit random number!!! Random rnd = new Random(); String idStr = ""; StringBuffer idBuf = new StringBuffer(); for ( int n=0; n < 4; n++ ) { int r = rnd.nextInt(); idBuf.append( Integer.toHexString( r ) ); } idStr = idBuf.toString(); DynaBean dbInfo = dbModel.createDynaBeanFor( "database_info", false ); dbInfo.set( "database_id", idStr ); dbInfo.set( "schema_version", new Integer( CURRENT_SCHEMA_VERSION ) ); dbInfo.set( "create_time", new Timestamp( System.currentTimeMillis() ) ); platform.insert( dbModel, dbInfo ); }
public void createDatabase( String user, String passwd ) { // Get the database schema XML file InputStream schemaIS = getClass().getClassLoader().getResourceAsStream( "photovault_schema.xml" ); Database dbModel = new DatabaseIO().read( new InputStreamReader( schemaIS ) ); // Create the datasource for accessing this database String driverName = "com.mysql.jdbc.Driver"; String dbUrl = "jdbc:mysql://" + getDbHost() + "/" + getDbName(); DataSource ds = null; if ( instanceType == TYPE_EMBEDDED ) { if ( !embeddedDirectory.exists() ) { embeddedDirectory.mkdirs(); } File derbyDir = new File( embeddedDirectory, "derby" ); File photoDir = new File( embeddedDirectory, "photos"); Volume vol = new Volume( "photos", photoDir.getAbsolutePath() ); addVolume( vol ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); driverName = "org.apache.derby.jdbc.EmbeddedDriver"; dbUrl = "jdbc:derby:photovault;create=true"; EmbeddedDataSource derbyDs = new EmbeddedDataSource(); derbyDs.setDatabaseName( "photovault" ); derbyDs.setCreateDatabase( "create" ); ds = derbyDs; } else { MysqlDataSource mysqlDs = new MysqlDataSource(); mysqlDs.setURL( dbUrl ); mysqlDs.setUser( user ); mysqlDs.setPassword( passwd ); ds = mysqlDs; } Platform platform = PlatformFactory.createNewPlatformInstance( ds ); /* * Do not use delimiters for the database object names in SQL statements. * This is to avoid case sensitivity problems with SQL92 compliant * databases like Derby - non-delimited identifiers are interpreted as case * insensitive. * * I am not sure if this is the correct way to solve the issue, however, * I am not willing to make a big change of schema definitions either. */ platform.getPlatformInfo().setDelimiterToken( "" ); platform.setUsername( user ); platform.setPassword( passwd ); platform.createTables( dbModel, true, true ); // Insert the seed data to database DataToDatabaseSink sink = new DataToDatabaseSink( platform, dbModel ); DataReader reader = new DataReader(); reader.setModel( dbModel ); reader.setSink( sink ); InputStream seedDataStream = this.getClass().getClassLoader().getResourceAsStream( "photovault_seed_data.xml" ); try { reader.parse( seedDataStream ); } catch (SAXException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } // Create the database // TODO: Since the seed has only 48 significant bits this id is not really an // 128-bit random number!!! Random rnd = new Random(); String idStr = ""; StringBuffer idBuf = new StringBuffer(); for ( int n=0; n < 4; n++ ) { int r = rnd.nextInt(); idBuf.append( Integer.toHexString( r ) ); } idStr = idBuf.toString(); DynaBean dbInfo = dbModel.createDynaBeanFor( "database_info", false ); dbInfo.set( "database_id", idStr ); dbInfo.set( "schema_version", new Integer( CURRENT_SCHEMA_VERSION ) ); dbInfo.set( "create_time", new Timestamp( System.currentTimeMillis() ) ); platform.insert( dbModel, dbInfo ); }
1,109,109
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); prefs = PrefsUtils.getUserPrefsNode(architectSession); UserSettings us; // must be done right away, because a static // initializer in this class effects BeanUtils // behaviour which the XML Digester relies // upon heavily //TypeMap.getInstance(); contentPane = (JComponent)getContentPane(); try { ConfigFile cf = ConfigFile.getDefaultInstance(); us = cf.read(getArchitectSession()); architectSession.setUserSettings(us); sprefs = architectSession.getUserSettings().getSwingSettings(); } catch (IOException e) { throw new ArchitectException("prefs.read", e); } while (us.getPlDotIni() == null) { String message; String[] options = new String[] {"Browse", "Create"}; if (us.getPlDotIniPath() == null) { message = "location is not set"; } else if (new File(us.getPlDotIniPath()).isFile()) { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n could not be read"; } else { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n does not exist"; } int choice = JOptionPane.showOptionDialog(null, "The Architect keeps its list of database connections" + "\nin a file called PL.INI. Your PL.INI "+message+"." + "\n\nYou can browse for an existing PL.INI file on your system" + "\nor allow the Architect to create a new one in your home directory." + "\n\nHint: If you are a Power*Loader Suite user, you should browse for" + "\nan existing PL.INI in your Power*Loader installation directory.", "Missing PL.INI", 0, JOptionPane.INFORMATION_MESSAGE, null, options, null); File newPlIniFile; if (choice == 0) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(ASUtils.INI_FILE_FILTER); fc.setDialogTitle("Locate your PL.INI file"); int fcChoice = fc.showOpenDialog(null); if (fcChoice == JFileChooser.APPROVE_OPTION) { newPlIniFile = fc.getSelectedFile(); } else { newPlIniFile = null; } } else { newPlIniFile = new File(System.getProperty("user.home"), "pl.ini"); } if (newPlIniFile != null) try { newPlIniFile.createNewFile(); us.setPlDotIniPath(newPlIniFile.getPath()); } catch (IOException e1) { logger.error("Caught IO exception while creating empty PL.INI at \"" +newPlIniFile.getPath()+"\"", e1); JOptionPane.showMessageDialog(null, "Failed to create file \""+newPlIniFile.getPath()+"\":\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } // Create actions aboutAction = new AboutAction(); newProjectAction = new AbstractAction("New Project", ASUtils.createJLFIcon("general/New","New Project",sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { try { closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } catch (Exception ex) { JOptionPane.showMessageDialog(ArchitectFrame.this, "Can't create new project: "+ex.getMessage()); logger.error("Got exception while creating new project", ex); } } } }; newProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "New"); newProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, accelMask)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); saveProjectAction = new AbstractAction("Save Project", ASUtils.createJLFIcon("general/Save", "Save Project", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(false, true); } }; saveProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save"); saveProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, accelMask)); saveProjectAsAction = new AbstractAction("Save Project As...", ASUtils.createJLFIcon("general/SaveAs", "Save Project As...", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(true, true); } }; saveProjectAsAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save As"); prefAction = new PreferencesAction(); projectSettingsAction = new ProjectSettingsAction(); projectSettingsAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, accelMask)); printAction = new PrintAction(); printAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P, accelMask)); zoomInAction = new ZoomAction(ZOOM_STEP); zoomOutAction = new ZoomAction(ZOOM_STEP * -1.0); zoomNormalAction = new AbstractAction("Reset Zoom", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { playpen.setZoom(1.0); } }; zoomNormalAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Reset Zoom"); undoAction = new UndoAction(); redoAction = new RedoAction(); autoLayoutAction = new AutoLayoutAction(); autoLayout = new FruchtermanReingoldForceLayout(); autoLayoutAction.setLayout(autoLayout); exportDDLAction = new ExportDDLAction(); compareDMAction = new CompareDMAction(); exportPLTransAction = new ExportPLTransAction(); quickStartAction = new QuickStartAction(); deleteSelectedAction = new DeleteSelectedAction(); createIdentifyingRelationshipAction = new CreateRelationshipAction(true); createNonIdentifyingRelationshipAction = new CreateRelationshipAction(false); editRelationshipAction = new EditRelationshipAction(); createTableAction = new CreateTableAction(); editColumnAction = new EditColumnAction(); insertColumnAction = new InsertColumnAction(); editTableAction = new EditTableAction(); searchReplaceAction = new SearchReplaceAction(); searchReplaceAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, accelMask)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(searchReplaceAction); menuBar.add(editMenu); // the connections menu is set up when a new project is created (because it depends on the current DBTree) connectionsMenu = new JMenu("Connections"); connectionsMenu.setMnemonic('c'); menuBar.add(connectionsMenu); JMenu etlMenu = new JMenu("ETL"); etlMenu.setMnemonic('l'); JMenu etlSubmenuOne = new JMenu("Power*Loader"); etlSubmenuOne.add(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(aboutAction); menuBar.add(helpMenu); setJMenuBar(menuBar); projectBar = new JToolBar(JToolBar.HORIZONTAL); ppBar = new JToolBar(JToolBar.VERTICAL); projectBar.add(newProjectAction); projectBar.add(openProjectAction); projectBar.add(saveProjectAction); projectBar.addSeparator(); projectBar.add(printAction); projectBar.addSeparator(); projectBar.add(undoAction); projectBar.add(redoAction); projectBar.addSeparator(); projectBar.add(exportDDLAction); projectBar.addSeparator(); projectBar.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.addSeparator(); tempButton = ppBar.add(deleteSelectedAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(createTableAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(insertColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); tempButton = ppBar.add(editColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); ppBar.add(createNonIdentifyingRelationshipAction); ppBar.add(createIdentifyingRelationshipAction); tempButton = ppBar.add(editRelationshipAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); Container projectBarPane = getContentPane(); projectBarPane.setLayout(new BorderLayout()); projectBarPane.add(projectBar, BorderLayout.NORTH); JPanel cp = new JPanel(new BorderLayout()); cp.add(ppBar, BorderLayout.EAST); projectBarPane.add(cp, BorderLayout.CENTER); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); cp.add(splitPane, BorderLayout.CENTER); logger.debug("Added splitpane to content pane"); splitPane.setDividerLocation (sprefs.getInt(SwingUserSettings.DIVIDER_LOCATION, 150)); //dbTree.getPreferredSize().width)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); prefs = PrefsUtils.getUserPrefsNode(architectSession); UserSettings us; // must be done right away, because a static // initializer in this class effects BeanUtils // behaviour which the XML Digester relies // upon heavily //TypeMap.getInstance(); contentPane = (JComponent)getContentPane(); try { ConfigFile cf = ConfigFile.getDefaultInstance(); us = cf.read(getArchitectSession()); architectSession.setUserSettings(us); sprefs = architectSession.getUserSettings().getSwingSettings(); } catch (IOException e) { throw new ArchitectException("prefs.read", e); } while (us.getPlDotIni() == null) { String message; String[] options = new String[] {"Browse", "Create"}; if (us.getPlDotIniPath() == null) { message = "location is not set"; } else if (new File(us.getPlDotIniPath()).isFile()) { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n could not be read"; } else { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n does not exist"; } int choice = JOptionPane.showOptionDialog(null, "The Architect keeps its list of database connections" + "\nin a file called PL.INI. Your PL.INI "+message+"." + "\n\nYou can browse for an existing PL.INI file on your system" + "\nor allow the Architect to create a new one in your home directory." + "\n\nHint: If you are a Power*Loader Suite user, you should browse for" + "\nan existing PL.INI in your Power*Loader installation directory.", "Missing PL.INI", 0, JOptionPane.INFORMATION_MESSAGE, null, options, null); File newPlIniFile; if (choice == 0) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(ASUtils.INI_FILE_FILTER); fc.setDialogTitle("Locate your PL.INI file"); int fcChoice = fc.showOpenDialog(null); if (fcChoice == JFileChooser.APPROVE_OPTION) { newPlIniFile = fc.getSelectedFile(); } else { newPlIniFile = null; } } else { newPlIniFile = new File(System.getProperty("user.home"), "pl.ini"); } if (newPlIniFile != null) try { newPlIniFile.createNewFile(); us.setPlDotIniPath(newPlIniFile.getPath()); } catch (IOException e1) { logger.error("Caught IO exception while creating empty PL.INI at \"" +newPlIniFile.getPath()+"\"", e1); JOptionPane.showMessageDialog(null, "Failed to create file \""+newPlIniFile.getPath()+"\":\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } // Create actions aboutAction = new AboutAction(); newProjectAction = new AbstractAction("New Project", ASUtils.createJLFIcon("general/New","New Project",sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { try { closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } catch (Exception ex) { JOptionPane.showMessageDialog(ArchitectFrame.this, "Can't create new project: "+ex.getMessage()); logger.error("Got exception while creating new project", ex); } } } }; newProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "New"); newProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, accelMask)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); saveProjectAction = new AbstractAction("Save Project", ASUtils.createJLFIcon("general/Save", "Save Project", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(false, true); } }; saveProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save"); saveProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, accelMask)); saveProjectAsAction = new AbstractAction("Save Project As...", ASUtils.createJLFIcon("general/SaveAs", "Save Project As...", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(true, true); } }; saveProjectAsAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save As"); prefAction = new PreferencesAction(); projectSettingsAction = new ProjectSettingsAction(); projectSettingsAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, accelMask)); printAction = new PrintAction(); printAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P, accelMask)); zoomInAction = new ZoomAction(ZOOM_STEP); zoomOutAction = new ZoomAction(ZOOM_STEP * -1.0); zoomNormalAction = new AbstractAction("Reset Zoom", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { playpen.setZoom(1.0); } }; zoomNormalAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Reset Zoom"); undoAction = new UndoAction(); redoAction = new RedoAction(); autoLayoutAction = new AutoLayoutAction(); autoLayout = new FruchtermanReingoldForceLayout(); autoLayoutAction.setLayout(autoLayout); exportDDLAction = new ExportDDLAction(); compareDMAction = new CompareDMAction(); exportPLTransAction = new ExportPLTransAction(); quickStartAction = new QuickStartAction(); deleteSelectedAction = new DeleteSelectedAction(); createIdentifyingRelationshipAction = new CreateRelationshipAction(true); createNonIdentifyingRelationshipAction = new CreateRelationshipAction(false); editRelationshipAction = new EditRelationshipAction(); createTableAction = new CreateTableAction(); editColumnAction = new EditColumnAction(); insertColumnAction = new InsertColumnAction(); editTableAction = new EditTableAction(); searchReplaceAction = new SearchReplaceAction(); searchReplaceAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, accelMask)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(searchReplaceAction); menuBar.add(editMenu); // the connections menu is set up when a new project is created (because it depends on the current DBTree) connectionsMenu = new JMenu("Connections"); connectionsMenu.setMnemonic('c'); menuBar.add(connectionsMenu); JMenu etlMenu = new JMenu("ETL"); etlMenu.setMnemonic('l'); JMenu etlSubmenuOne = new JMenu("Power*Loader"); etlSubmenuOne.add(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(aboutAction); menuBar.add(helpMenu); setJMenuBar(menuBar); projectBar = new JToolBar(JToolBar.HORIZONTAL); ppBar = new JToolBar(JToolBar.VERTICAL); projectBar.add(newProjectAction); projectBar.add(openProjectAction); projectBar.add(saveProjectAction); projectBar.addSeparator(); projectBar.add(printAction); projectBar.addSeparator(); projectBar.add(undoAction); projectBar.add(redoAction); projectBar.addSeparator(); projectBar.add(exportDDLAction); projectBar.addSeparator(); projectBar.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.addSeparator(); tempButton = ppBar.add(deleteSelectedAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(createTableAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(insertColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); tempButton = ppBar.add(editColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); ppBar.add(createNonIdentifyingRelationshipAction); ppBar.add(createIdentifyingRelationshipAction); tempButton = ppBar.add(editRelationshipAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); Container projectBarPane = getContentPane(); projectBarPane.setLayout(new BorderLayout()); projectBarPane.add(projectBar, BorderLayout.NORTH); JPanel cp = new JPanel(new BorderLayout()); cp.add(ppBar, BorderLayout.EAST); projectBarPane.add(cp, BorderLayout.CENTER); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); cp.add(splitPane, BorderLayout.CENTER); logger.debug("Added splitpane to content pane"); splitPane.setDividerLocation (sprefs.getInt(SwingUserSettings.DIVIDER_LOCATION, 150)); //dbTree.getPreferredSize().width)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
1,109,112
public void setProject(SwingUIProject p) throws ArchitectException { this.project = p; logger.debug("Setting project to "+project); setTitle(project.getName()+" - Power*Architect"); playpen = project.getPlayPen(); dbTree = project.getSourceDatabases(); setupActions(); setupConnectionsMenu(); splitPane.setLeftComponent(new JScrollPane(dbTree)); splitPane.setRightComponent(new JScrollPane(playpen)); }
public void setProject(SwingUIProject p) throws ArchitectException { this.project = p; logger.debug("Setting project to "+project); setTitle(project.getName()+" - Power*Architect"); playpen = project.getPlayPen(); dbTree = project.getSourceDatabases(); setupActions(); setupConnectionsMenu(); splitPane.setLeftComponent(new JScrollPane(dbTree)); splitPane.setRightComponent(new JScrollPane(playpen)); splitPane.setDividerLocation(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); }
1,109,114
public void addNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ RMINotificationListener notifListener = toRMINotificationListener(listener); notifications.put(listener, notifListener); NotificationFilter notifFilter = toJMXNotificationFilter(filter); try { rmiAdaptor.addNotificationListener(toJMXObjectName(objectName), notifListener, notifFilter, handback); } catch (Exception e) { throw new RuntimeException(e); } }
public void addNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ RMINotificationListener notifListener = toRMINotificationListener(listener); notifications.put(listener, notifListener); NotificationFilter notifFilter = toJMXNotificationFilter(filter); try { rmiAdaptor.addNotificationListener(toJMXObjectName(objectName), notifListener, notifFilter, handback); } catch (Exception e) { throw new RuntimeException(e); } }
1,109,115
public void addNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ RMINotificationListener notifListener = toRMINotificationListener(listener); notifications.put(listener, notifListener); NotificationFilter notifFilter = toJMXNotificationFilter(filter); try { rmiAdaptor.addNotificationListener(toJMXObjectName(objectName), notifListener, notifFilter, handback); } catch (Exception e) { throw new RuntimeException(e); } }
public void addNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ RMINotificationListener notifListener = toRMINotificationListener(listener); notifications.put(listener, notifListener); NotificationFilter notifFilter = toJMXNotificationFilter(filter); try { rmiAdaptor.addNotificationListener(toJMXObjectName(objectName), notifListener, notifFilter, new String()); } catch (Exception e) { throw new RuntimeException(e); } }
1,109,116
public void removeNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ RMINotificationListener notifListener = (RMINotificationListener)notifications.remove(listener); assert notifListener != null; try { rmiAdaptor.removeNotificationListener(toJMXObjectName(objectName), notifListener); } catch (Exception e) { throw new RuntimeException(e); } }
public void removeNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ RMINotificationListener notifListener = (RMINotificationListener)notifications.remove(listener); assert notifListener != null; try { rmiAdaptor.removeNotificationListener(toJMXObjectName(objectName), notifListener); } catch (Exception e) { throw new RuntimeException(e); } }
1,109,117
private static RMINotificationListener toRMINotificationListener( final ObjectNotificationListener listener){ return new MyRMINotificationListener(listener); }
private static RMINotificationListener toRMINotificationListener( final ObjectNotificationListener listener){ return new MyRMINotificationListener(listener); }
1,109,119
public void addNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ throw new RuntimeException("Notifications not supported"); }
public void addNotificationListener(ObjectName objectName, ObjectNotificationListener listener, ObjectNotificationFilter filter, Object handback){ NotificationListener notifListener = toJMXNotificationListener(listener); notifications.put(listener, notifListener); NotificationFilter notifFilter = toJMXNotificationFilter(filter); notifFilters.put(filter, notifFilter); Class[] methodSignature = new Class[]{javax.management.ObjectName.class, NotificationListener.class, NotificationFilter.class, Object.class}; Object[] methodArgs = new Object[]{toJMXObjectName(objectName), notifListener, notifFilter, handback}; callMBeanServer("addNotificationListener", methodSignature, methodArgs); }
1,109,120
public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals(READ_GENOTYPES)){ ReadDataDialog readDialog = new ReadDataDialog("Open new data", this); readDialog.pack(); readDialog.setVisible(true); } else if (command.equals(READ_MARKERS)){ //JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.setSelectedFile(new File("")); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { readMarkers(fc.getSelectedFile(),null); } }else if (command.equals(READ_ANALYSIS_TRACK)){ fc.setSelectedFile(new File("")); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION){ readAnalysisFile(fc.getSelectedFile()); } }else if (command.equals(DOWNLOAD_GBROWSE)){ GBrowseDialog gbd = new GBrowseDialog(this, "Connect to HapMap Info Server"); gbd.pack(); gbd.setVisible(true); }else if (command.equals(GBROWSE_OPTS)){ GBrowseOptionDialog gbod = new GBrowseOptionDialog(this, "HapMap Info Track Options"); gbod.pack(); gbod.setVisible(true); }else if (command.equals(READ_BLOCKS_FILE)){ fc.setSelectedFile(new File("")); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){ readBlocksFile(fc.getSelectedFile()); } }else if (command.equals(CUST_BLOCKS)){ TweakBlockDefsDialog tweakDialog = new TweakBlockDefsDialog("Customize Blocks", this); tweakDialog.pack(); tweakDialog.setVisible(true); }else if (command.equals(CLEAR_BLOCKS)){ changeBlocks(BLOX_NONE); //blockdef clauses }else if (command.startsWith("block")){ int method = Integer.valueOf(command.substring(5)).intValue(); changeBlocks(method); //zooming clauses }else if (command.startsWith("zoom")){ dPrimeDisplay.zoom(Integer.valueOf(command.substring(4)).intValue()); //coloring clauses }else if (command.startsWith("color")){ Options.setLDColorScheme(Integer.valueOf(command.substring(5)).intValue()); dPrimeDisplay.colorDPrime(); changeKey(); //exporting clauses }else if (command.equals(EXPORT_PNG)){ export((HaploviewTab)tabs.getSelectedComponent(), PNG_MODE, 0, Chromosome.getUnfilteredSize()); }else if (command.equals(EXPORT_TEXT)){ export((HaploviewTab)tabs.getSelectedComponent(), TXT_MODE, 0, Chromosome.getUnfilteredSize()); }else if (command.equals(EXPORT_OPTIONS)){ ExportDialog exDialog = new ExportDialog(this); exDialog.pack(); exDialog.setVisible(true); }else if (command.equals("Select All")){ checkPanel.selectAll(); }else if (command.equals("Rescore Markers")){ String cut = cdc.hwcut.getText(); if (cut.equals("")){ cut = "0"; } CheckData.hwCut = Double.parseDouble(cut); cut = cdc.genocut.getText(); if (cut.equals("")){ cut="0"; } CheckData.failedGenoCut = Integer.parseInt(cut); cut = cdc.mendcut.getText(); if (cut.equals("")){ cut="0"; } CheckData.numMendErrCut = Integer.parseInt(cut); cut = cdc.mafcut.getText(); if (cut.equals("")){ cut="0"; } CheckData.mafCut = Double.parseDouble(cut); checkPanel.redoRatings(); JTable jt = checkPanel.getTable(); jt.repaint(); }else if (command.equals("LD Display Spacing")){ ProportionalSpacingDialog spaceDialog = new ProportionalSpacingDialog(this, "Adjust LD Spacing"); spaceDialog.pack(); spaceDialog.setVisible(true); }else if (command.equals("About Haploview")){ JOptionPane.showMessageDialog(this, ABOUT_STRING, "About Haploview", JOptionPane.INFORMATION_MESSAGE); } else if(command.equals("Check for update")) { final SwingWorker worker = new SwingWorker(){ UpdateChecker uc; String unableToConnect; public Object construct() { uc = new UpdateChecker(); try { uc.checkForUpdate(); } catch(IOException ioe) { unableToConnect = ioe.getMessage(); } return null; } public void finished() { window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); if(uc != null) { if(unableToConnect != null) { JOptionPane.showMessageDialog(window, "An error occured while checking for update.\n " + unableToConnect , "Update Check", JOptionPane.ERROR_MESSAGE); } else if(uc.isNewVersionAvailable()) { UpdateDisplayDialog udp = new UpdateDisplayDialog(window,"Update Check",uc); udp.pack(); udp.setVisible(true); } else { JOptionPane.showMessageDialog(window, "Your version of Haploview is up to date.", "Update Check", JOptionPane.INFORMATION_MESSAGE); } } } }; setCursor(new Cursor(Cursor.WAIT_CURSOR)); worker.start(); }else if (command.equals("Quit")){ quit(); } else { for (int i = 0; i < viewItems.length; i++) { if (command.equals(viewItems[i])) tabs.setSelectedIndex(i); } } }
public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals(READ_GENOTYPES)){ ReadDataDialog readDialog = new ReadDataDialog("Open new data", this); readDialog.pack(); readDialog.setVisible(true); } else if (command.equals(READ_MARKERS)){ //JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.setSelectedFile(new File("")); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { readMarkers(fc.getSelectedFile(),null); } }else if (command.equals(READ_ANALYSIS_TRACK)){ fc.setSelectedFile(new File("")); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION){ readAnalysisFile(fc.getSelectedFile()); } }else if (command.equals(DOWNLOAD_GBROWSE)){ GBrowseDialog gbd = new GBrowseDialog(this, "Connect to HapMap Info Server"); gbd.pack(); gbd.setVisible(true); }else if (command.equals(GBROWSE_OPTS)){ GBrowseOptionDialog gbod = new GBrowseOptionDialog(this, "HapMap Info Track Options"); gbod.pack(); gbod.setVisible(true); }else if (command.equals(READ_BLOCKS_FILE)){ fc.setSelectedFile(new File("")); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){ readBlocksFile(fc.getSelectedFile()); } }else if (command.equals(CUST_BLOCKS)){ TweakBlockDefsDialog tweakDialog = new TweakBlockDefsDialog("Customize Blocks", this); tweakDialog.pack(); tweakDialog.setVisible(true); }else if (command.equals(CLEAR_BLOCKS)){ changeBlocks(BLOX_NONE); //blockdef clauses }else if (command.startsWith("block")){ int method = Integer.valueOf(command.substring(5)).intValue(); changeBlocks(method); //zooming clauses }else if (command.startsWith("zoom")){ dPrimeDisplay.zoom(Integer.valueOf(command.substring(4)).intValue()); //coloring clauses }else if (command.startsWith("color")){ Options.setLDColorScheme(Integer.valueOf(command.substring(5)).intValue()); dPrimeDisplay.colorDPrime(); changeKey(); //exporting clauses }else if (command.equals(EXPORT_PNG)){ export((HaploviewTab)tabs.getSelectedComponent(), PNG_MODE, 0, Chromosome.getUnfilteredSize()); }else if (command.equals(EXPORT_TEXT)){ export((HaploviewTab)tabs.getSelectedComponent(), TXT_MODE, 0, Chromosome.getUnfilteredSize()); }else if (command.equals(EXPORT_OPTIONS)){ ExportDialog exDialog = new ExportDialog(this); exDialog.pack(); exDialog.setVisible(true); }else if (command.equals("Select All")){ checkPanel.selectAll(); }else if (command.equals("Rescore Markers")){ String cut = cdc.hwcut.getText(); if (cut.equals("")){ cut = "0"; } CheckData.hwCut = Double.parseDouble(cut); cut = cdc.genocut.getText(); if (cut.equals("")){ cut="0"; } CheckData.failedGenoCut = Integer.parseInt(cut); cut = cdc.mendcut.getText(); if (cut.equals("")){ cut="0"; } CheckData.numMendErrCut = Integer.parseInt(cut); cut = cdc.mafcut.getText(); if (cut.equals("")){ cut="0"; } CheckData.mafCut = Double.parseDouble(cut); checkPanel.redoRatings(); JTable jt = checkPanel.getTable(); jt.repaint(); }else if (command.equals("LD Display Spacing")){ ProportionalSpacingDialog spaceDialog = new ProportionalSpacingDialog(this, "Adjust LD Spacing"); spaceDialog.pack(); spaceDialog.setVisible(true); }else if (command.equals("About Haploview")){ JOptionPane.showMessageDialog(this, ABOUT_STRING, "About Haploview", JOptionPane.INFORMATION_MESSAGE); } else if(command.equals("Check for update")) { final SwingWorker worker = new SwingWorker(){ UpdateChecker uc; String unableToConnect; public Object construct() { uc = new UpdateChecker(); try { uc.checkForUpdate(); } catch(IOException ioe) { unableToConnect = ioe.getMessage(); } return null; } public void finished() { window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); if(uc != null) { if(unableToConnect != null) { JOptionPane.showMessageDialog(window, "An error occured while checking for update.\n " + unableToConnect , "Update Check", JOptionPane.ERROR_MESSAGE); } else if(uc.isNewVersionAvailable()) { UpdateDisplayDialog udp = new UpdateDisplayDialog(window,"Update Check",uc); udp.pack(); udp.setVisible(true); } else { JOptionPane.showMessageDialog(window, "Your version of Haploview is up to date.", "Update Check", JOptionPane.INFORMATION_MESSAGE); } } } }; setCursor(new Cursor(Cursor.WAIT_CURSOR)); worker.start(); }else if (command.equals("Quit")){ quit(); } else { for (int i = 0; i < viewItems.length; i++) { if (command.equals(viewItems[i])) tabs.setSelectedIndex(i); } } }
1,109,122
public String getShortHelp(){ return "Exit from jManage command prompt mode"; }
public String getShortHelp(){ return "Exits from jManage command prompt mode"; }
1,109,123
void prepareMarkerInput(File infile, long md, String[][] hapmapGoodies) throws IOException, HaploViewException{ //this method is called to gather data about the markers used. //It is assumed that the input file is two columns, the first being //the name and the second the absolute position. the maxdist is //used to determine beyond what distance comparisons will not be //made. if the infile param is null, loads up "dummy info" for //situation where no info file exists Vector names = new Vector(); Vector positions = new Vector(); maxdist = md; negMaxdist = -1 * maxdist; try{ if (infile != null){ if (infile.length() < 1){ throw new HaploViewException("Info file is empty or does not exist: " + infile.getName()); } String currentLine; long prevloc = -1000000000; //read the input file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; while ((currentLine = in.readLine()) != null){ StringTokenizer st = new StringTokenizer(currentLine); if (st.countTokens() > 1){ lineCount++; }else if (st.countTokens() == 1){ //complain if only one field found throw new HaploViewException("Info file format error on line "+lineCount+ ":\n Info file must be of format: <markername> <markerposition>"); }else{ //skip blank lines continue; } String name = st.nextToken(); String l = st.nextToken(); long loc; try{ loc = Long.parseLong(l); }catch (NumberFormatException nfe){ throw new HaploViewException("Info file format error on line "+lineCount+ ":\n\"" + l + "\" should be of type long." + "\n Info file must be of format: <markername> <markerposition>"); } if (loc < prevloc){ throw new HaploViewException("Info file out of order:\n"+ name); } prevloc = loc; names.add(name); positions.add(l); } if (lineCount > Chromosome.getSize()){ throw(new HaploViewException("Info file error:\nMarker number mismatch: too many\nmarkers in info file.")); } if (lineCount < Chromosome.getSize()){ throw(new HaploViewException("Info file error:\nMarker number mismatch: too few\nmarkers in info file.")); } infoKnown=true; } if (hapmapGoodies != null){ //we know some stuff from the hapmap so we'll add it here for (int x=0; x < hapmapGoodies.length; x++){ names.add(hapmapGoodies[x][0]); positions.add(hapmapGoodies[x][1]); } infoKnown = true; } }catch (HaploViewException e){ throw(e); }finally{ double numChroms = chromosomes.size(); Vector markerInfo = new Vector(); double[] numBadGenotypes = new double[Chromosome.getSize()]; percentBadGenotypes = new double[Chromosome.getSize()]; for (int i = 0; i < Chromosome.getSize(); i++){ //to compute maf, browse chrom list and count instances of each allele byte a1 = 0; byte a2 = 0; double numa1 = 0; double numa2 = 0; for (int j = 0; j < chromosomes.size(); j++){ //if there is a data point for this marker on this chromosome byte thisAllele = ((Chromosome)chromosomes.elementAt(j)).getGenotype(i); if (!(thisAllele == 0)){ if (thisAllele >= 5){ numa1+=0.5; numa2+=0.5; if (thisAllele < 9){ if (a1==0){ a1 = (byte)(thisAllele-4); }else if (a2 == 0){ if (!(thisAllele-5 == a1)){ a2 = (byte)(thisAllele-4); } } } }else if (a1 == 0){ a1 = thisAllele; numa1++; }else if (thisAllele == a1){ numa1++; }else{ numa2++; a2 = thisAllele; } } else { numBadGenotypes[i]++; } } if (numa2 > numa1){ byte temp = a1; a1 = a2; a2 = temp; } double maf = numa1/(numa2+numa1); if (maf > 0.5) maf = 1.0-maf; if (infoKnown){ markerInfo.add(new SNP((String)names.elementAt(i), Long.parseLong((String)positions.elementAt(i)), Math.rint(maf*100.0)/100.0, a1, a2)); }else{ markerInfo.add(new SNP("Marker " + String.valueOf(i+1), (i*4000), Math.rint(maf*100.0)/100.0,a1,a2)); } percentBadGenotypes[i] = numBadGenotypes[i]/numChroms; } Chromosome.markers = markerInfo.toArray(); } }
void prepareMarkerInput(File infile, long md, String[][] hapmapGoodies) throws IOException, HaploViewException{ //this method is called to gather data about the markers used. //It is assumed that the input file is two columns, the first being //the name and the second the absolute position. the maxdist is //used to determine beyond what distance comparisons will not be //made. if the infile param is null, loads up "dummy info" for //situation where no info file exists Vector names = new Vector(); Vector positions = new Vector(); maxdist = md; negMaxdist = -1 * maxdist; try{ if (infile != null){ if (infile.length() < 1){ throw new HaploViewException("Info file is empty or does not exist: " + infile.getName()); } String currentLine; long prevloc = -1000000000; //read the input file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; while ((currentLine = in.readLine()) != null){ StringTokenizer st = new StringTokenizer(currentLine); if (st.countTokens() > 1){ lineCount++; }else if (st.countTokens() == 1){ //complain if only one field found throw new HaploViewException("Info file format error on line "+lineCount+ ":\n Info file must be of format: <markername> <markerposition>"); }else{ //skip blank lines continue; } String name = st.nextToken(); String l = st.nextToken(); long loc; try{ loc = Long.parseLong(l); }catch (NumberFormatException nfe){ throw new HaploViewException("Info file format error on line "+lineCount+ ":\n\"" + l + "\" should be of type long." + "\n Info file must be of format: <markername> <markerposition>"); } if (loc < prevloc){ throw new HaploViewException("Info file out of order:\n"+ name); } prevloc = loc; names.add(name); positions.add(l); } if (lineCount > Chromosome.getSize()){ throw(new HaploViewException("Info file error:\nMarker number mismatch: too many\nmarkers in info file.")); } if (lineCount < Chromosome.getSize()){ throw(new HaploViewException("Info file error:\nMarker number mismatch: too few\nmarkers in info file.")); } infoKnown=true; } if (hapmapGoodies != null){ //we know some stuff from the hapmap so we'll add it here for (int x=0; x < hapmapGoodies.length; x++){ names.add(hapmapGoodies[x][0]); positions.add(hapmapGoodies[x][1]); } infoKnown = true; } }catch (HaploViewException e){ throw(e); }finally{ double numChroms = chromosomes.size(); Vector markerInfo = new Vector(); double[] numBadGenotypes = new double[Chromosome.getSize()]; percentBadGenotypes = new double[Chromosome.getSize()]; for (int i = 0; i < Chromosome.getSize(); i++){ //to compute maf, browse chrom list and count instances of each allele byte a1 = 0; byte a2 = 0; double numa1 = 0; double numa2 = 0; for (int j = 0; j < chromosomes.size(); j++){ //if there is a data point for this marker on this chromosome byte thisAllele = ((Chromosome)chromosomes.elementAt(j)).getGenotype(i); if (!(thisAllele == 0)){ if (thisAllele >= 5){ numa1+=0.5; numa2+=0.5; if (thisAllele < 9){ if (a1==0){ a1 = (byte)(thisAllele-4); }else if (a2 == 0){ if (!(thisAllele-4 == a1)){ a2 = (byte)(thisAllele-4); } } } }else if (a1 == 0){ a1 = thisAllele; numa1++; }else if (thisAllele == a1){ numa1++; }else{ numa2++; a2 = thisAllele; } } else { numBadGenotypes[i]++; } } if (numa2 > numa1){ byte temp = a1; a1 = a2; a2 = temp; } double maf = numa1/(numa2+numa1); if (maf > 0.5) maf = 1.0-maf; if (infoKnown){ markerInfo.add(new SNP((String)names.elementAt(i), Long.parseLong((String)positions.elementAt(i)), Math.rint(maf*100.0)/100.0, a1, a2)); }else{ markerInfo.add(new SNP("Marker " + String.valueOf(i+1), (i*4000), Math.rint(maf*100.0)/100.0,a1,a2)); } percentBadGenotypes[i] = numBadGenotypes[i]/numChroms; } Chromosome.markers = markerInfo.toArray(); } }
1,109,126
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
public void adjustDisplay(int dt){ //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
1,109,127
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
1,109,128
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > dt){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
1,109,129
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); numhaps++; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
1,109,130
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
1,109,131
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
1,109,132
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filteredHaplos.length)) return; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
public void adjustDisplay() { //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh filteredHaplos = new Haplotype[orderedHaplos.length][]; boolean atLeastOneHap = false; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > displayThresh){ tempVector.add(orderedHaplos[i][j]); atLeastOneHap=true; } } if (atLeastOneHap){ printable++; atLeastOneHap=false; } filteredHaplos[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filteredHaplos[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filts.length)){ JOptionPane.showMessageDialog(this.getParent(), "Error: At least one block has too few haplotypes of frequency > " + dt, "Error", JOptionPane.ERROR_MESSAGE); return; } //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); repaint(); }
1,109,133
public void getHaps() throws HaploViewException{ if (theData.blocks == null) {return;} Haplotype[][] haplos = theData.generateHaplotypes(theData.blocks, 0); orderedHaplos = new Haplotype[haplos.length][]; for (int i = 0; i < haplos.length; i++) { Vector orderedHaps = new Vector(); //step through each haplotype in this block for (int hapCount = 0; hapCount < haplos[i].length; hapCount++) { if (orderedHaps.size() == 0) { orderedHaps.add(haplos[i][hapCount]); } else { for (int j = 0; j < orderedHaps.size(); j++) { if (((Haplotype)(orderedHaps.elementAt(j))).getPercentage() < haplos[i][hapCount].getPercentage()) { orderedHaps.add(j, haplos[i][hapCount]); break; } if ((j+1) == orderedHaps.size()) { orderedHaps.add(haplos[i][hapCount]); break; } } } } orderedHaplos[i] = new Haplotype[orderedHaps.size()]; orderedHaps.copyInto(orderedHaplos[i]); } adjustDisplay(); }
public void getHaps() throws HaploViewException{ if (theData.blocks == null) {return;} Haplotype[][] haplos = theData.generateHaplotypes(theData.blocks, 0); orderedHaplos = new Haplotype[haplos.length][]; for (int i = 0; i < haplos.length; i++) { Vector orderedHaps = new Vector(); //step through each haplotype in this block for (int hapCount = 0; hapCount < haplos[i].length; hapCount++) { if (orderedHaps.size() == 0) { orderedHaps.add(haplos[i][hapCount]); } else { for (int j = 0; j < orderedHaps.size(); j++) { if (((Haplotype)(orderedHaps.elementAt(j))).getPercentage() < haplos[i][hapCount].getPercentage()) { orderedHaps.add(j, haplos[i][hapCount]); break; } if ((j+1) == orderedHaps.size()) { orderedHaps.add(haplos[i][hapCount]); break; } } } } orderedHaplos[i] = new Haplotype[orderedHaps.size()]; orderedHaps.copyInto(orderedHaplos[i]); } adjustDisplay(displayThresh); }
1,109,135
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
1,109,136
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
1,109,137
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
1,109,138
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
public int compare(CompositeScore<?> first, CompositeScore<?> second) { int result = FilteringScore.nullCompare(first, second); if (result != 0) { return result; } result = FilteringScore.rangeComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); if (result != 0) { return result; } result = OrderingScore.fullComparator() .compare(first.getOrderingScore(), second.getOrderingScore()); if (result != 0) { return result; } result = FilteringScore.fullComparator() .compare(first.getFilteringScore(), second.getFilteringScore()); return result; }
1,109,139
public static <S extends Storable> OrderingScore<S> evaluate (OrderedProperty<S>[] indexProperties, boolean unique, boolean clustered, Filter<S> filter, OrderingList<S> ordering) { if (indexProperties == null) { throw new IllegalArgumentException("Index properties required"); } // Get filter list early to detect errors. List<PropertyFilter<S>> filterList = PropertyFilterList.get(filter); if (ordering == null) { ordering = OrderingList.emptyList(); } // Ordering properties which match identity filters don't affect order // results. Build up this set to find them quickly. Set<ChainedProperty<S>> identityPropSet = new HashSet<ChainedProperty<S>>(filterList.size()); for (PropertyFilter<S> propFilter : filterList) { if (propFilter.getOperator() == RelOp.EQ) { identityPropSet.add(propFilter.getChainedProperty()); } } OrderingList<S> handledOrdering = OrderingList.emptyList(); OrderingList<S> remainderOrdering = OrderingList.emptyList(); OrderingList<S> freeOrdering = OrderingList.emptyList(); OrderingList<S> unusedOrdering = OrderingList.emptyList(); // Build up list of unused properties that were filtered out. for (int i=0; i<indexProperties.length; i++) { OrderedProperty<S> indexProp = indexProperties[i]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (identityPropSet.contains(indexChained)) { unusedOrdering = unusedOrdering.concat(indexProp.direction(UNSPECIFIED)); } } // If index is unique and every property is matched by an identity // filter, then there won't be any handled or remainder properties. uniquelyCheck: if (unique) { for (int i=0; i<indexProperties.length; i++) { ChainedProperty<S> indexChained = indexProperties[i].getChainedProperty(); if (!identityPropSet.contains(indexChained)) { // Missed a property, so ordering is still relevant. break uniquelyCheck; } } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, // no handled properties remainderOrdering, // no remainder properties false, // no need to reverse order freeOrdering, // no free properties unusedOrdering); } Boolean shouldReverseOrder = null; Set<ChainedProperty<S>> seen = new HashSet<ChainedProperty<S>>(); boolean gap = false; int indexPos = 0; calcScore: for (int i=0; i<ordering.size(); i++) { OrderedProperty<S> property = ordering.get(i); ChainedProperty<S> chained = property.getChainedProperty(); if (seen.contains(chained)) { // Redundant property doesn't affect ordering. continue calcScore; } seen.add(chained); if (identityPropSet.contains(chained)) { // Doesn't affect ordering. continue calcScore; } indexPosMatch: while (!gap && indexPos < indexProperties.length) { OrderedProperty<S> indexProp = indexProperties[indexPos]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (chained.equals(indexChained)) { Direction indexDir = indexProp.getDirection(); if (indexDir == UNSPECIFIED) { // Assume index natural order is ascending. indexDir = ASCENDING; } if (shouldReverseOrder != null && shouldReverseOrder) { indexDir = indexDir.reverse(); } if (property.getDirection() == UNSPECIFIED) { // Set handled property direction to match index. property = property.direction(indexDir); } else if (shouldReverseOrder == null) { shouldReverseOrder = indexDir != property.getDirection(); // Any properies already in the list had been // originally unspecified. They might need to be // reversed now. if (shouldReverseOrder) { handledOrdering = handledOrdering.reverseDirections(); } } else if (indexDir != property.getDirection()) { // Direction mismatch, so cannot be handled. break indexPosMatch; } handledOrdering = handledOrdering.concat(property); indexPos++; continue calcScore; } if (identityPropSet.contains(indexChained)) { // Even though ordering did not match index at current // position, the search for handled propertes can continue if // index gap matches an identity filter. indexPos++; continue indexPosMatch; } // Index gap, so cannot be handled. break indexPosMatch; } // Property not handled and not an identity filter. remainderOrdering = remainderOrdering.concat(property); gap = true; } // Walk through all remaining index properties and list them as free. while (indexPos < indexProperties.length) { OrderedProperty<S> freeProp = indexProperties[indexPos]; ChainedProperty<S> freeChained = freeProp.getChainedProperty(); // Don't list as free if already listed as unused. if (!identityPropSet.contains(freeChained)) { if (shouldReverseOrder == null) { freeProp = freeProp.direction(UNSPECIFIED); } else { Direction freePropDir = freePropDir = freeProp.getDirection(); if (freePropDir == UNSPECIFIED) { freePropDir = ASCENDING; } if (shouldReverseOrder) { freeProp = freeProp.direction(freePropDir.reverse()); } } freeOrdering = freeOrdering.concat(freeProp); } indexPos++; } if (shouldReverseOrder == null) { shouldReverseOrder = false; } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, remainderOrdering, shouldReverseOrder, freeOrdering, unusedOrdering); }
public static <S extends Storable> OrderingScore<S> evaluate (OrderedProperty<S>[] indexProperties, boolean unique, boolean clustered, Filter<S> filter, OrderingList<S> ordering) { if (indexProperties == null) { throw new IllegalArgumentException("Index properties required"); } // Get filter list early to detect errors. List<PropertyFilter<S>> filterList = PropertyFilterList.get(filter); if (ordering == null) { ordering = OrderingList.emptyList(); } // Ordering properties which match identity filters don't affect order // results. Build up this set to find them quickly. Set<ChainedProperty<S>> identityPropSet = new HashSet<ChainedProperty<S>>(filterList.size()); for (PropertyFilter<S> propFilter : filterList) { if (propFilter.getOperator() == RelOp.EQ) { identityPropSet.add(propFilter.getChainedProperty()); } } OrderingList<S> handledOrdering = OrderingList.emptyList(); OrderingList<S> remainderOrdering = OrderingList.emptyList(); OrderingList<S> freeOrdering = OrderingList.emptyList(); OrderingList<S> unusedOrdering = OrderingList.emptyList(); // Build up list of unused properties that were filtered out. for (int i=0; i<indexProperties.length; i++) { OrderedProperty<S> indexProp = indexProperties[i]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (identityPropSet.contains(indexChained)) { unusedOrdering = unusedOrdering.concat(indexProp.direction(UNSPECIFIED)); } } // If index is unique and every property is matched by an identity // filter, then there won't be any handled or remainder properties. uniquelyCheck: if (unique) { for (int i=0; i<indexProperties.length; i++) { ChainedProperty<S> indexChained = indexProperties[i].getChainedProperty(); if (!identityPropSet.contains(indexChained)) { // Missed a property, so ordering is still relevant. break uniquelyCheck; } } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, // no handled properties remainderOrdering, // no remainder properties false, // no need to reverse order freeOrdering, // no free properties unusedOrdering); } Boolean shouldReverseOrder = null; Set<ChainedProperty<S>> seen = new HashSet<ChainedProperty<S>>(); boolean gap = false; int indexPos = 0; calcScore: for (int i=0; i<ordering.size(); i++) { OrderedProperty<S> property = ordering.get(i); ChainedProperty<S> chained = property.getChainedProperty(); if (seen.contains(chained)) { // Redundant property doesn't affect ordering. continue calcScore; } seen.add(chained); if (identityPropSet.contains(chained)) { // Doesn't affect ordering. continue calcScore; } indexPosMatch: while (!gap && indexPos < indexProperties.length) { OrderedProperty<S> indexProp = indexProperties[indexPos]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (chained.equals(indexChained)) { Direction indexDir = indexProp.getDirection(); if (indexDir == UNSPECIFIED) { // Assume index natural order is ascending. indexDir = ASCENDING; } if (shouldReverseOrder != null && shouldReverseOrder) { indexDir = indexDir.reverse(); } if (property.getDirection() == UNSPECIFIED) { // Set handled property direction to match index. property = property.direction(indexDir); } else if (shouldReverseOrder == null) { shouldReverseOrder = indexDir != property.getDirection(); // Any properies already in the list had been // originally unspecified. They might need to be // reversed now. if (shouldReverseOrder) { handledOrdering = handledOrdering.reverseDirections(); } } else if (indexDir != property.getDirection()) { // Direction mismatch, so cannot be handled. break indexPosMatch; } handledOrdering = handledOrdering.concat(property); indexPos++; continue calcScore; } if (identityPropSet.contains(indexChained)) { // Even though ordering did not match index at current // position, the search for handled propertes can continue if // index gap matches an identity filter. indexPos++; continue indexPosMatch; } // Index gap, so cannot be handled. break indexPosMatch; } // Property not handled and not an identity filter. remainderOrdering = remainderOrdering.concat(property); gap = true; } // Walk through all remaining index properties and list them as free. while (indexPos < indexProperties.length) { OrderedProperty<S> freeProp = indexProperties[indexPos]; ChainedProperty<S> freeChained = freeProp.getChainedProperty(); // Don't list as free if already listed as unused. if (!identityPropSet.contains(freeChained)) { if (shouldReverseOrder == null) { freeProp = freeProp.direction(UNSPECIFIED); } else { Direction freePropDir = freePropDir = freeProp.getDirection(); if (freePropDir == UNSPECIFIED) { freePropDir = ASCENDING; } if (shouldReverseOrder) { freeProp = freeProp.direction(freePropDir.reverse()); } } freeOrdering = freeOrdering.concat(freeProp); } indexPos++; } if (shouldReverseOrder == null) { shouldReverseOrder = false; } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, remainderOrdering, shouldReverseOrder, freeOrdering, unusedOrdering); }
1,109,140
public static <S extends Storable> OrderingScore<S> evaluate (OrderedProperty<S>[] indexProperties, boolean unique, boolean clustered, Filter<S> filter, OrderingList<S> ordering) { if (indexProperties == null) { throw new IllegalArgumentException("Index properties required"); } // Get filter list early to detect errors. List<PropertyFilter<S>> filterList = PropertyFilterList.get(filter); if (ordering == null) { ordering = OrderingList.emptyList(); } // Ordering properties which match identity filters don't affect order // results. Build up this set to find them quickly. Set<ChainedProperty<S>> identityPropSet = new HashSet<ChainedProperty<S>>(filterList.size()); for (PropertyFilter<S> propFilter : filterList) { if (propFilter.getOperator() == RelOp.EQ) { identityPropSet.add(propFilter.getChainedProperty()); } } OrderingList<S> handledOrdering = OrderingList.emptyList(); OrderingList<S> remainderOrdering = OrderingList.emptyList(); OrderingList<S> freeOrdering = OrderingList.emptyList(); OrderingList<S> unusedOrdering = OrderingList.emptyList(); // Build up list of unused properties that were filtered out. for (int i=0; i<indexProperties.length; i++) { OrderedProperty<S> indexProp = indexProperties[i]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (identityPropSet.contains(indexChained)) { unusedOrdering = unusedOrdering.concat(indexProp.direction(UNSPECIFIED)); } } // If index is unique and every property is matched by an identity // filter, then there won't be any handled or remainder properties. uniquelyCheck: if (unique) { for (int i=0; i<indexProperties.length; i++) { ChainedProperty<S> indexChained = indexProperties[i].getChainedProperty(); if (!identityPropSet.contains(indexChained)) { // Missed a property, so ordering is still relevant. break uniquelyCheck; } } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, // no handled properties remainderOrdering, // no remainder properties false, // no need to reverse order freeOrdering, // no free properties unusedOrdering); } Boolean shouldReverseOrder = null; Set<ChainedProperty<S>> seen = new HashSet<ChainedProperty<S>>(); boolean gap = false; int indexPos = 0; calcScore: for (int i=0; i<ordering.size(); i++) { OrderedProperty<S> property = ordering.get(i); ChainedProperty<S> chained = property.getChainedProperty(); if (seen.contains(chained)) { // Redundant property doesn't affect ordering. continue calcScore; } seen.add(chained); if (identityPropSet.contains(chained)) { // Doesn't affect ordering. continue calcScore; } indexPosMatch: while (!gap && indexPos < indexProperties.length) { OrderedProperty<S> indexProp = indexProperties[indexPos]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (chained.equals(indexChained)) { Direction indexDir = indexProp.getDirection(); if (indexDir == UNSPECIFIED) { // Assume index natural order is ascending. indexDir = ASCENDING; } if (shouldReverseOrder != null && shouldReverseOrder) { indexDir = indexDir.reverse(); } if (property.getDirection() == UNSPECIFIED) { // Set handled property direction to match index. property = property.direction(indexDir); } else if (shouldReverseOrder == null) { shouldReverseOrder = indexDir != property.getDirection(); // Any properies already in the list had been // originally unspecified. They might need to be // reversed now. if (shouldReverseOrder) { handledOrdering = handledOrdering.reverseDirections(); } } else if (indexDir != property.getDirection()) { // Direction mismatch, so cannot be handled. break indexPosMatch; } handledOrdering = handledOrdering.concat(property); indexPos++; continue calcScore; } if (identityPropSet.contains(indexChained)) { // Even though ordering did not match index at current // position, the search for handled propertes can continue if // index gap matches an identity filter. indexPos++; continue indexPosMatch; } // Index gap, so cannot be handled. break indexPosMatch; } // Property not handled and not an identity filter. remainderOrdering = remainderOrdering.concat(property); gap = true; } // Walk through all remaining index properties and list them as free. while (indexPos < indexProperties.length) { OrderedProperty<S> freeProp = indexProperties[indexPos]; ChainedProperty<S> freeChained = freeProp.getChainedProperty(); // Don't list as free if already listed as unused. if (!identityPropSet.contains(freeChained)) { if (shouldReverseOrder == null) { freeProp = freeProp.direction(UNSPECIFIED); } else { Direction freePropDir = freePropDir = freeProp.getDirection(); if (freePropDir == UNSPECIFIED) { freePropDir = ASCENDING; } if (shouldReverseOrder) { freeProp = freeProp.direction(freePropDir.reverse()); } } freeOrdering = freeOrdering.concat(freeProp); } indexPos++; } if (shouldReverseOrder == null) { shouldReverseOrder = false; } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, remainderOrdering, shouldReverseOrder, freeOrdering, unusedOrdering); }
public static <S extends Storable> OrderingScore<S> evaluate (OrderedProperty<S>[] indexProperties, boolean unique, boolean clustered, Filter<S> filter, OrderingList<S> ordering) { if (indexProperties == null) { throw new IllegalArgumentException("Index properties required"); } // Get filter list early to detect errors. List<PropertyFilter<S>> filterList = PropertyFilterList.get(filter); if (ordering == null) { ordering = OrderingList.emptyList(); } // Ordering properties which match identity filters don't affect order // results. Build up this set to find them quickly. Set<ChainedProperty<S>> identityPropSet = new HashSet<ChainedProperty<S>>(filterList.size()); for (PropertyFilter<S> propFilter : filterList) { if (propFilter.getOperator() == RelOp.EQ) { identityPropSet.add(propFilter.getChainedProperty()); } } OrderingList<S> handledOrdering = OrderingList.emptyList(); OrderingList<S> remainderOrdering = OrderingList.emptyList(); OrderingList<S> freeOrdering = OrderingList.emptyList(); OrderingList<S> unusedOrdering = OrderingList.emptyList(); // Build up list of unused properties that were filtered out. for (int i=0; i<indexProperties.length; i++) { OrderedProperty<S> indexProp = indexProperties[i]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (identityPropSet.contains(indexChained)) { unusedOrdering = unusedOrdering.concat(indexProp.direction(UNSPECIFIED)); } } // If index is unique and every property is matched by an identity // filter, then there won't be any handled or remainder properties. uniquelyCheck: if (unique) { for (int i=0; i<indexProperties.length; i++) { ChainedProperty<S> indexChained = indexProperties[i].getChainedProperty(); if (!identityPropSet.contains(indexChained)) { // Missed a property, so ordering is still relevant. break uniquelyCheck; } } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, // no handled properties remainderOrdering, // no remainder properties false, // no need to reverse order freeOrdering, // no free properties unusedOrdering); } Boolean shouldReverseOrder = null; Set<ChainedProperty<S>> seen = new HashSet<ChainedProperty<S>>(); boolean gap = false; int indexPos = 0; calcScore: for (int i=0; i<ordering.size(); i++) { OrderedProperty<S> property = ordering.get(i); ChainedProperty<S> chained = property.getChainedProperty(); if (seen.contains(chained)) { // Redundant property doesn't affect ordering. continue calcScore; } seen.add(chained); if (identityPropSet.contains(chained)) { // Doesn't affect ordering. continue calcScore; } indexPosMatch: while (!gap && indexPos < indexProperties.length) { OrderedProperty<S> indexProp = indexProperties[indexPos]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (chained.equals(indexChained)) { Direction indexDir = indexProp.getDirection(); if (indexDir == UNSPECIFIED) { // Assume index natural order is ascending. indexDir = ASCENDING; } if (shouldReverseOrder != null && shouldReverseOrder) { indexDir = indexDir.reverse(); } if (property.getDirection() == UNSPECIFIED) { // Set handled property direction to match index. property = property.direction(indexDir); } else if (shouldReverseOrder == null) { shouldReverseOrder = indexDir != property.getDirection(); // Any properies already in the list had been // originally unspecified. They might need to be // reversed now. if (shouldReverseOrder) { handledOrdering = handledOrdering.reverseDirections(); } } else if (indexDir != property.getDirection()) { // Direction mismatch, so cannot be handled. break indexPosMatch; } handledOrdering = handledOrdering.concat(property); indexPos++; continue calcScore; } if (identityPropSet.contains(indexChained)) { // Even though ordering did not match index at current // position, the search for handled propertes can continue if // index gap matches an identity filter. indexPos++; continue indexPosMatch; } // Index gap, so cannot be handled. break indexPosMatch; } // Property not handled and not an identity filter. remainderOrdering = remainderOrdering.concat(property); gap = true; } // Walk through all remaining index properties and list them as free. while (indexPos < indexProperties.length) { OrderedProperty<S> freeProp = indexProperties[indexPos]; ChainedProperty<S> freeChained = freeProp.getChainedProperty(); // Don't list as free if already listed as unused. if (!identityPropSet.contains(freeChained)) { if (shouldReverseOrder == null) { freeProp = freeProp.direction(UNSPECIFIED); } else { Direction freePropDir = freePropDir = freeProp.getDirection(); if (freePropDir == UNSPECIFIED) { freePropDir = ASCENDING; } if (shouldReverseOrder) { freeProp = freeProp.direction(freePropDir.reverse()); } } freeOrdering = freeOrdering.concat(freeProp); } indexPos++; } if (shouldReverseOrder == null) { shouldReverseOrder = false; } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, remainderOrdering, shouldReverseOrder, freeOrdering, unusedOrdering); }
1,109,141
public static <S extends Storable> OrderingScore<S> evaluate (OrderedProperty<S>[] indexProperties, boolean unique, boolean clustered, Filter<S> filter, OrderingList<S> ordering) { if (indexProperties == null) { throw new IllegalArgumentException("Index properties required"); } // Get filter list early to detect errors. List<PropertyFilter<S>> filterList = PropertyFilterList.get(filter); if (ordering == null) { ordering = OrderingList.emptyList(); } // Ordering properties which match identity filters don't affect order // results. Build up this set to find them quickly. Set<ChainedProperty<S>> identityPropSet = new HashSet<ChainedProperty<S>>(filterList.size()); for (PropertyFilter<S> propFilter : filterList) { if (propFilter.getOperator() == RelOp.EQ) { identityPropSet.add(propFilter.getChainedProperty()); } } OrderingList<S> handledOrdering = OrderingList.emptyList(); OrderingList<S> remainderOrdering = OrderingList.emptyList(); OrderingList<S> freeOrdering = OrderingList.emptyList(); OrderingList<S> unusedOrdering = OrderingList.emptyList(); // Build up list of unused properties that were filtered out. for (int i=0; i<indexProperties.length; i++) { OrderedProperty<S> indexProp = indexProperties[i]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (identityPropSet.contains(indexChained)) { unusedOrdering = unusedOrdering.concat(indexProp.direction(UNSPECIFIED)); } } // If index is unique and every property is matched by an identity // filter, then there won't be any handled or remainder properties. uniquelyCheck: if (unique) { for (int i=0; i<indexProperties.length; i++) { ChainedProperty<S> indexChained = indexProperties[i].getChainedProperty(); if (!identityPropSet.contains(indexChained)) { // Missed a property, so ordering is still relevant. break uniquelyCheck; } } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, // no handled properties remainderOrdering, // no remainder properties false, // no need to reverse order freeOrdering, // no free properties unusedOrdering); } Boolean shouldReverseOrder = null; Set<ChainedProperty<S>> seen = new HashSet<ChainedProperty<S>>(); boolean gap = false; int indexPos = 0; calcScore: for (int i=0; i<ordering.size(); i++) { OrderedProperty<S> property = ordering.get(i); ChainedProperty<S> chained = property.getChainedProperty(); if (seen.contains(chained)) { // Redundant property doesn't affect ordering. continue calcScore; } seen.add(chained); if (identityPropSet.contains(chained)) { // Doesn't affect ordering. continue calcScore; } indexPosMatch: while (!gap && indexPos < indexProperties.length) { OrderedProperty<S> indexProp = indexProperties[indexPos]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (chained.equals(indexChained)) { Direction indexDir = indexProp.getDirection(); if (indexDir == UNSPECIFIED) { // Assume index natural order is ascending. indexDir = ASCENDING; } if (shouldReverseOrder != null && shouldReverseOrder) { indexDir = indexDir.reverse(); } if (property.getDirection() == UNSPECIFIED) { // Set handled property direction to match index. property = property.direction(indexDir); } else if (shouldReverseOrder == null) { shouldReverseOrder = indexDir != property.getDirection(); // Any properies already in the list had been // originally unspecified. They might need to be // reversed now. if (shouldReverseOrder) { handledOrdering = handledOrdering.reverseDirections(); } } else if (indexDir != property.getDirection()) { // Direction mismatch, so cannot be handled. break indexPosMatch; } handledOrdering = handledOrdering.concat(property); indexPos++; continue calcScore; } if (identityPropSet.contains(indexChained)) { // Even though ordering did not match index at current // position, the search for handled propertes can continue if // index gap matches an identity filter. indexPos++; continue indexPosMatch; } // Index gap, so cannot be handled. break indexPosMatch; } // Property not handled and not an identity filter. remainderOrdering = remainderOrdering.concat(property); gap = true; } // Walk through all remaining index properties and list them as free. while (indexPos < indexProperties.length) { OrderedProperty<S> freeProp = indexProperties[indexPos]; ChainedProperty<S> freeChained = freeProp.getChainedProperty(); // Don't list as free if already listed as unused. if (!identityPropSet.contains(freeChained)) { if (shouldReverseOrder == null) { freeProp = freeProp.direction(UNSPECIFIED); } else { Direction freePropDir = freePropDir = freeProp.getDirection(); if (freePropDir == UNSPECIFIED) { freePropDir = ASCENDING; } if (shouldReverseOrder) { freeProp = freeProp.direction(freePropDir.reverse()); } } freeOrdering = freeOrdering.concat(freeProp); } indexPos++; } if (shouldReverseOrder == null) { shouldReverseOrder = false; } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, remainderOrdering, shouldReverseOrder, freeOrdering, unusedOrdering); }
public static <S extends Storable> OrderingScore<S> evaluate (OrderedProperty<S>[] indexProperties, boolean unique, boolean clustered, Filter<S> filter, OrderingList<S> ordering) { if (indexProperties == null) { throw new IllegalArgumentException("Index properties required"); } // Get filter list early to detect errors. List<PropertyFilter<S>> filterList = PropertyFilterList.get(filter); if (ordering == null) { ordering = OrderingList.emptyList(); } // Ordering properties which match identity filters don't affect order // results. Build up this set to find them quickly. Set<ChainedProperty<S>> identityPropSet = new HashSet<ChainedProperty<S>>(filterList.size()); for (PropertyFilter<S> propFilter : filterList) { if (propFilter.getOperator() == RelOp.EQ) { identityPropSet.add(propFilter.getChainedProperty()); } } OrderingList<S> handledOrdering = OrderingList.emptyList(); OrderingList<S> remainderOrdering = OrderingList.emptyList(); OrderingList<S> freeOrdering = OrderingList.emptyList(); OrderingList<S> unusedOrdering = OrderingList.emptyList(); // Build up list of unused properties that were filtered out. for (int i=0; i<indexProperties.length; i++) { OrderedProperty<S> indexProp = indexProperties[i]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (identityPropSet.contains(indexChained)) { unusedOrdering = unusedOrdering.concat(indexProp.direction(UNSPECIFIED)); } } // If index is unique and every property is matched by an identity // filter, then there won't be any handled or remainder properties. uniquelyCheck: if (unique) { for (int i=0; i<indexProperties.length; i++) { ChainedProperty<S> indexChained = indexProperties[i].getChainedProperty(); if (!identityPropSet.contains(indexChained)) { // Missed a property, so ordering is still relevant. break uniquelyCheck; } } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, // no handled properties remainderOrdering, // no remainder properties false, // no need to reverse order freeOrdering, // no free properties unusedOrdering); } Boolean shouldReverseOrder = null; Set<ChainedProperty<S>> seen = new HashSet<ChainedProperty<S>>(); boolean gap = false; int indexPos = 0; calcScore: for (int i=0; i<ordering.size(); i++) { OrderedProperty<S> property = ordering.get(i); ChainedProperty<S> chained = property.getChainedProperty(); if (seen.contains(chained)) { // Redundant property doesn't affect ordering. continue calcScore; } seen.add(chained); if (identityPropSet.contains(chained)) { // Doesn't affect ordering. continue calcScore; } indexPosMatch: while (!gap && indexPos < indexProperties.length) { OrderedProperty<S> indexProp = indexProperties[indexPos]; ChainedProperty<S> indexChained = indexProp.getChainedProperty(); if (chained.equals(indexChained)) { Direction indexDir = indexProp.getDirection(); if (indexDir == UNSPECIFIED) { // Assume index natural order is ascending. indexDir = ASCENDING; } if (shouldReverseOrder != null && shouldReverseOrder) { indexDir = indexDir.reverse(); } if (property.getDirection() == UNSPECIFIED) { // Set handled property direction to match index. property = property.direction(indexDir); } else if (shouldReverseOrder == null) { shouldReverseOrder = indexDir != property.getDirection(); // Any properies already in the list had been // originally unspecified. They might need to be // reversed now. if (shouldReverseOrder) { handledOrdering = handledOrdering.reverseDirections(); } } else if (indexDir != property.getDirection()) { // Direction mismatch, so cannot be handled. break indexPosMatch; } handledOrdering = handledOrdering.concat(property); indexPos++; continue calcScore; } if (identityPropSet.contains(indexChained)) { // Even though ordering did not match index at current // position, the search for handled propertes can continue if // index gap matches an identity filter. indexPos++; continue indexPosMatch; } // Index gap, so cannot be handled. break indexPosMatch; } // Property not handled and not an identity filter. remainderOrdering = remainderOrdering.concat(property); gap = true; } // Walk through all remaining index properties and list them as free. while (indexPos < indexProperties.length) { OrderedProperty<S> freeProp = indexProperties[indexPos]; ChainedProperty<S> freeChained = freeProp.getChainedProperty(); // Don't list as free if already listed as unused. if (!identityPropSet.contains(freeChained)) { if (shouldReverseOrder == null) { freeProp = freeProp.direction(UNSPECIFIED); } else { Direction freePropDir = freePropDir = freeProp.getDirection(); if (freePropDir == UNSPECIFIED) { freePropDir = ASCENDING; } if (shouldReverseOrder) { freeProp = freeProp.direction(freePropDir.reverse()); } } freeOrdering = freeOrdering.concat(freeProp); } indexPos++; } if (shouldReverseOrder == null) { shouldReverseOrder = false; } return new OrderingScore<S>(clustered, indexProperties.length, handledOrdering, remainderOrdering, shouldReverseOrder, freeOrdering, unusedOrdering); }
1,109,142
protected void ensureNotInMapping(SQLColumn pkcol) throws ArchitectException { if (containsPkColumn(pkcol)) { ColumnMapping m = getMappingByPkCol(pkcol); List fkTies = fkTable.keysOfColumn(m.getFkColumn()); if (fkTies == null || fkTies.size() <= 1) { fkTable.removeColumn(m.getFkColumn()); } removeChild(m); } }
protected void ensureNotInMapping(SQLColumn pkcol) throws ArchitectException { if (containsPkColumn(pkcol)) { ColumnMapping m = getMappingByPkCol(pkcol); List fkTies = fkTable.keysOfColumn(m.getFkColumn()); if (fkTies == null || fkTies.size() <= 1) { fkTable.removeColumn(m.getFkColumn()); } } }
1,109,144
public void populate() throws ArchitectException { logger.debug("SQLRelationship: populate is a no-op"); }
public void populate() { logger.debug("SQLRelationship: populate is a no-op"); }
1,109,145
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
1,109,146
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
1,109,147
public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
1,109,148
public void doTag(XMLOutput output) throws Exception { if (var == null) { throw new IllegalArgumentException("The var attribute cannot be null"); } Document document = null; if (xml == null) { SAXContentHandler handler = new SAXContentHandler(); XMLOutput newOutput = new XMLOutput(handler); handler.startDocument(); getBody().run(context, newOutput); handler.endDocument(); document = handler.getDocument(); /* // the following is inefficient as it requires a parse of the text // but is left here in the code to see how it could be done. String text = getBodyText(); if ( log.isDebugEnabled() ) { log.debug( "About to parse: " + text ); } document = getSAXReader().read( new StringReader( text ) ); */ } else { if (xml instanceof String) { document = getSAXReader().read((String) xml); } else if (xml instanceof Reader) { document = getSAXReader().read((Reader) xml); } else if (xml instanceof InputStream) { document = getSAXReader().read((InputStream) xml); } else if (xml instanceof URL) { document = getSAXReader().read((URL) xml); } else { throw new IllegalArgumentException( "Invalid xml argument. Must be a String, Reader, InputStream or URL." + " Was type; " + xml.getClass().getName() + " with value: " + xml); } } context.setVariable(var, document); }
public void doTag(XMLOutput output) throws Exception { if (var == null) { throw new IllegalArgumentException("The var attribute cannot be null"); } Document document = null; if (xml == null) { SAXContentHandler handler = new SAXContentHandler(); XMLOutput newOutput = new XMLOutput(handler); handler.startDocument(); invokeBody( newOutput); handler.endDocument(); document = handler.getDocument(); /* // the following is inefficient as it requires a parse of the text // but is left here in the code to see how it could be done. String text = getBodyText(); if ( log.isDebugEnabled() ) { log.debug( "About to parse: " + text ); } document = getSAXReader().read( new StringReader( text ) ); */ } else { if (xml instanceof String) { document = getSAXReader().read((String) xml); } else if (xml instanceof Reader) { document = getSAXReader().read((Reader) xml); } else if (xml instanceof InputStream) { document = getSAXReader().read((InputStream) xml); } else if (xml instanceof URL) { document = getSAXReader().read((URL) xml); } else { throw new IllegalArgumentException( "Invalid xml argument. Must be a String, Reader, InputStream or URL." + " Was type; " + xml.getClass().getName() + " with value: " + xml); } } context.setVariable(var, document); }
1,109,151
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; } if (zoomLevel == 0){ printDetails = true; } else{ printDetails = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); if (size.height < pref.height){ setSize(pref); } //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.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.black); 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]; } } } */ if (theData.infoKnown) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations int lineSpan = (dPrimeTable.length-1) * boxSize; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; 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; } //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; } // 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.getMarker(last).getPosition() - Chromosome.getMarker(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 if (noImage){ //first time through draw a worldmap if dataset is big: final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); 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(this.getBackground()); 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()); double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); 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); } } //draw block display in worldmap gw2.setColor(this.getBackground()); 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; } noImage = false; } 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); wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height); //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); } }
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; } if (zoomLevel == 0){ printDetails = true; } else{ printDetails = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); if (size.height < pref.height){ setSize(pref); } //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.setColor(BG_GREY); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.black); 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]; } } } */ if (theData.infoKnown) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations int lineSpan = (dPrimeTable.length-1) * boxSize; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; 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; } //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; } // 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.getMarker(last).getPosition() - Chromosome.getMarker(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 if (noImage){ //first time through draw a worldmap if dataset is big: final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); 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(this.getBackground()); 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()); double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); 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); } } //draw block display in worldmap gw2.setColor(this.getBackground()); 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; } noImage = false; } 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); wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height); //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); } }
1,109,152
public PresentationObject getAccounts(IWContext iwc) { DataTable T = new DataTable(); T.setWidth("100%"); String styp = ""; Collection accounts = null; if (topic > 0) { accounts = MailFinder.getInstance().getTopicAccounts(topic); styp = iwrb.getLocalizedString("list.topic", "topic"); EmailTopic tpc = (EmailTopic) topics.get(String.valueOf(topic)); if(tpc !=null) styp += " " + tpc.getName(); } /*else if (group > 0) { accounts = MailFinder.getInstance().getGroupAccounts(group); styp = iwrb.getLocalizedString("list.group", "group"); EmailGroup grp = (EmailGroup) groups.get(String.valueOf(group)); if(grp!=null) styp += " " + grp.getName(); }*/ String title = iwrb.getLocalizedString("list.accounts", "Accounts"); title += " " + iwrb.getLocalizedString("list.in", "in") + " " + styp + " "; T.addTitle(title); T.setTitlesHorizontal(true); int row = 1; Text tName = tf.format(iwrb.getLocalizedString("name", "Name")); Text tHost = tf.format(iwrb.getLocalizedString("host", "Host")); Text tUser = tf.format(iwrb.getLocalizedString("user", "User")); Text tPass = tf.format(iwrb.getLocalizedString("pass", "Passwd")); Text tProto = tf.format(iwrb.getLocalizedString("protocol", "Protocol")); row++; TextInput name = new TextInput("name"); TextInput host = new TextInput("host"); TextInput user = new TextInput("user"); TextInput pass = new TextInput("pass"); DropdownMenu proto = getProtocolDropdown("proto", ""); //DropdownMenu grps = getGroupDropdown("grp", ""); if (accounts != null && accounts.size() > 0) { java.util.Iterator iter = accounts.iterator(); EmailAccount acc; Link deleteLink; Link accountLink; Link editLink; int id; while (iter.hasNext()) { acc = (EmailAccount) iter.next(); id = Integer.parseInt(acc.toString()); if (id == account && EditObject.equals("account")) { name.setContent(acc.getName()); host.setContent(acc.getHost()); user.setContent(acc.getUser()); pass.setContent(acc.getPassword()); proto.setSelectedElement(String.valueOf(acc.getProtocol())); T.add(tName, 1, row); T.add(name, 2, row++); T.add(tHost, 1, row); T.add(host, 2, row++); T.add(tUser, 1, row); T.add(user, 2, row++); T.add(tPass, 1, row); T.add(pass, 2, row++); T.add(tProto, 1, row); T.add(proto, 2, row++); T.add(new HiddenInput(prmAccountId, String.valueOf(id))); formAdded = true; } else { accountLink = new Link(tf.format(acc.getName())); accountLink.addParameter(prmInstanceId, String.valueOf(instance)); accountLink.addParameter(prmAccountId, id); //accountLink.addParameter(prmGroupId, group); accountLink.addParameter(prmTopicId, topic); editLink = new Link((Image) editImage.clone()); editLink.addParameter(prmInstanceId, String.valueOf(instance)); editLink.addParameter(prmAccountId, id); editLink.addParameter(prmEdit, "account"); //editLink.addParameter(prmGroupId, group); editLink.addParameter(prmTopicId, topic); deleteLink = new Link((Image) deleteImage.clone()); deleteLink.addParameter(prmInstanceId, String.valueOf(instance)); deleteLink.addParameter(prmAccountId, id); deleteLink.addParameter(prmDel, "account"); //deleteLink.addParameter(prmGroupId, group); deleteLink.addParameter(prmTopicId, topic); T.add(accountLink, 1, row); T.add(editLink, 2, row); T.add(deleteLink, 2, row); row++; T.add(tHost, 1, row); T.add(tf.format(acc.getHost()), 2, row++); T.add(tUser, 1, row); T.add(tf.format(acc.getUser()), 2, row++); T.add(tPass, 1, row); T.add(tf.format(acc.getPassword()), 2, row++); T.add(tProto, 1, row); T.add(tf.format(getProtocolName(acc.getProtocol())), 2, row++); } row++; } } if (!formAdded && NewObject.equals("account")) { T.add(tName, 1, row); T.add(name, 2, row++); T.add(tHost, 1, row); T.add(host, 2, row++); T.add(tUser, 1, row); T.add(user, 2, row++); T.add(tPass, 1, row); T.add(pass, 2, row++); T.add(tProto, 1, row); T.add(proto, 2, row++); formAdded = true; } else { Link li = new Link(iwrb.getLocalizedImageButton("new", "New")); li.addParameter(prmInstanceId, String.valueOf(instance)); //li.addParameter(prmGroupId, group); li.addParameter(prmTopicId, topic); li.addParameter(prmNew, "account"); T.addButton(li); } if (formAdded) { T.addButton(new SubmitButton(iwrb.getLocalizedImageButton("save", "Save"), "save", "account")); } return T; }
public PresentationObject getAccounts(IWContext iwc) { DataTable T = new DataTable(); T.setWidth("100%"); String styp = ""; Collection accounts = null; if (topic > 0) { accounts = MailFinder.getInstance().getTopicAccounts(topic); styp = iwrb.getLocalizedString("list.topic", "topic"); EmailTopic tpc = (EmailTopic) topics.get(String.valueOf(topic)); if(tpc !=null) styp += " " + tpc.getName(); } /*else if (group > 0) { accounts = MailFinder.getInstance().getGroupAccounts(group); styp = iwrb.getLocalizedString("list.group", "group"); EmailGroup grp = (EmailGroup) groups.get(String.valueOf(group)); if(grp!=null) styp += " " + grp.getName(); }*/ String title = iwrb.getLocalizedString("list.accounts", "Accounts"); title += " " + iwrb.getLocalizedString("list.in", "in") + " " + styp + " "; T.addTitle(title); T.setTitlesHorizontal(true); int row = 1; Text tName = tf.format(iwrb.getLocalizedString("name", "Name")); Text tHost = tf.format(iwrb.getLocalizedString("host", "Host")); Text tUser = tf.format(iwrb.getLocalizedString("user", "User")); Text tPass = tf.format(iwrb.getLocalizedString("pass", "Passwd")); Text tProto = tf.format(iwrb.getLocalizedString("protocol", "Protocol")); row++; TextInput name = new TextInput("name"); TextInput host = new TextInput("host"); TextInput user = new TextInput("user"); TextInput pass = new TextInput("pass"); DropdownMenu proto = getProtocolDropdown("proto", ""); //DropdownMenu grps = getGroupDropdown("grp", ""); if (accounts != null && accounts.size() > 0) { java.util.Iterator iter = accounts.iterator(); EmailAccount acc; Link deleteLink; Link accountLink; Link editLink; int id; while (iter.hasNext()) { acc = (EmailAccount) iter.next(); id = acc.getIdentifier().intValue(); if (id == account && EditObject.equals("account")) { name.setContent(acc.getName()); host.setContent(acc.getHost()); user.setContent(acc.getUser()); pass.setContent(acc.getPassword()); proto.setSelectedElement(String.valueOf(acc.getProtocol())); T.add(tName, 1, row); T.add(name, 2, row++); T.add(tHost, 1, row); T.add(host, 2, row++); T.add(tUser, 1, row); T.add(user, 2, row++); T.add(tPass, 1, row); T.add(pass, 2, row++); T.add(tProto, 1, row); T.add(proto, 2, row++); T.add(new HiddenInput(prmAccountId, String.valueOf(id))); formAdded = true; } else { accountLink = new Link(tf.format(acc.getName())); accountLink.addParameter(prmInstanceId, String.valueOf(instance)); accountLink.addParameter(prmAccountId, id); //accountLink.addParameter(prmGroupId, group); accountLink.addParameter(prmTopicId, topic); editLink = new Link((Image) editImage.clone()); editLink.addParameter(prmInstanceId, String.valueOf(instance)); editLink.addParameter(prmAccountId, id); editLink.addParameter(prmEdit, "account"); //editLink.addParameter(prmGroupId, group); editLink.addParameter(prmTopicId, topic); deleteLink = new Link((Image) deleteImage.clone()); deleteLink.addParameter(prmInstanceId, String.valueOf(instance)); deleteLink.addParameter(prmAccountId, id); deleteLink.addParameter(prmDel, "account"); //deleteLink.addParameter(prmGroupId, group); deleteLink.addParameter(prmTopicId, topic); T.add(accountLink, 1, row); T.add(editLink, 2, row); T.add(deleteLink, 2, row); row++; T.add(tHost, 1, row); T.add(tf.format(acc.getHost()), 2, row++); T.add(tUser, 1, row); T.add(tf.format(acc.getUser()), 2, row++); T.add(tPass, 1, row); T.add(tf.format(acc.getPassword()), 2, row++); T.add(tProto, 1, row); T.add(tf.format(getProtocolName(acc.getProtocol())), 2, row++); } row++; } } if (!formAdded && NewObject.equals("account")) { T.add(tName, 1, row); T.add(name, 2, row++); T.add(tHost, 1, row); T.add(host, 2, row++); T.add(tUser, 1, row); T.add(user, 2, row++); T.add(tPass, 1, row); T.add(pass, 2, row++); T.add(tProto, 1, row); T.add(proto, 2, row++); formAdded = true; } else { Link li = new Link(iwrb.getLocalizedImageButton("new", "New")); li.addParameter(prmInstanceId, String.valueOf(instance)); //li.addParameter(prmGroupId, group); li.addParameter(prmTopicId, topic); li.addParameter(prmNew, "account"); T.addButton(li); } if (formAdded) { T.addButton(new SubmitButton(iwrb.getLocalizedImageButton("save", "Save"), "save", "account")); } return T; }
1,109,153
public PresentationObject getTopicsOverView(IWContext iwc){ Table T = new Table(); int row = 1; T.add(getTopicLink(-1,iwrb.getLocalizedString("new_topic","New topic")),1,row); row++; T.add(tf.format(iwrb.getLocalizedString("name","Name"),tf.HEADER),1,row); T.add(tf.format(iwrb.getLocalizedString("category","Category"),tf.HEADER),2,row); T.add(tf.format(iwrb.getLocalizedString("mail_server","Mail server"),tf.HEADER),3,row); T.add(tf.format(iwrb.getLocalizedString("subscribers","Subscribers"),tf.HEADER),4,row); T.add(tf.format(iwrb.getLocalizedString("welcome","Welcome"),tf.HEADER),5,row); row++; if(!topics.isEmpty()){ Iterator iter = topics.values().iterator(); EmailTopic topic; ICCategory category; EmailAccount account; EmailLetter welcome; Collection welcomes; Collection accounts; int emailCount; int topicID; while(iter.hasNext()){ topic = (EmailTopic) iter.next(); topicID = topic.getIdentifier().intValue(); T.add(getTopicLink(topicID,topic.getName()),1,row); category = (ICCategory) categories.get(Integer.toString(topic.getCategoryId())); T.add(tf.format(category.getName()),2,row); accounts = MailFinder.getInstance().getTopicAccounts(topicID,MailProtocol.SMTP); if(accounts!=null && !accounts.isEmpty()){ account = (EmailAccount) accounts.iterator().next(); T.add(getAccountLink(topicID,Integer.parseInt( account.toString()),account.getHost()),3,row); } else{ T.add(getAccountLink(topicID,-1,"X"),3,row); } emailCount = MailFinder.getInstance().getListEmailsCount(topic.getListId()); T.add((getSubscribersLink(topicID,String.valueOf(emailCount))),4,row); welcomes = MailFinder.getInstance().getEmailLetters(topicID,MailLetter.TYPE_SUBSCRIPTION); if(welcomes!=null && !welcomes.isEmpty()){ welcome = (MailLetter) welcomes.iterator().next(); T.add(getWelcomeLetterLink(Integer.parseInt(welcome.toString()),topicID,welcome.getSubject()),5,row); //T.add(tf.format(welcome.getSubject()),5,row); } else{ T.add(getWelcomeLetterLink(-1,topicID,"X"),5,row); } row++; } } return T; }
public PresentationObject getTopicsOverView(IWContext iwc){ Table T = new Table(); int row = 1; T.add(getTopicLink(-1,iwrb.getLocalizedString("new_topic","New topic")),1,row); row++; T.add(tf.format(iwrb.getLocalizedString("name","Name"),tf.HEADER),1,row); T.add(tf.format(iwrb.getLocalizedString("category","Category"),tf.HEADER),2,row); T.add(tf.format(iwrb.getLocalizedString("mail_server","Mail server"),tf.HEADER),3,row); T.add(tf.format(iwrb.getLocalizedString("subscribers","Subscribers"),tf.HEADER),4,row); T.add(tf.format(iwrb.getLocalizedString("welcome","Welcome"),tf.HEADER),5,row); row++; if(!topics.isEmpty()){ Iterator iter = topics.values().iterator(); EmailTopic topic; ICCategory category; EmailAccount account; EmailLetter welcome; Collection welcomes; Collection accounts; int emailCount; int topicID; while(iter.hasNext()){ topic = (EmailTopic) iter.next(); topicID = topic.getIdentifier().intValue(); T.add(getTopicLink(topicID,topic.getName()),1,row); category = (ICCategory) categories.get(Integer.toString(topic.getCategoryId())); T.add(tf.format(category.getName()),2,row); accounts = MailFinder.getInstance().getTopicAccounts(topicID,MailProtocol.SMTP); if(accounts!=null && !accounts.isEmpty()){ account = (EmailAccount) accounts.iterator().next(); T.add(getAccountLink(topicID,( account.getIdentifier().intValue()),account.getHost()),3,row); } else{ T.add(getAccountLink(topicID,-1,"X"),3,row); } emailCount = MailFinder.getInstance().getListEmailsCount(topic.getListId()); T.add((getSubscribersLink(topicID,String.valueOf(emailCount))),4,row); welcomes = MailFinder.getInstance().getEmailLetters(topicID,MailLetter.TYPE_SUBSCRIPTION); if(welcomes!=null && !welcomes.isEmpty()){ welcome = (MailLetter) welcomes.iterator().next(); T.add(getWelcomeLetterLink(Integer.parseInt(welcome.toString()),topicID,welcome.getSubject()),5,row); //T.add(tf.format(welcome.getSubject()),5,row); } else{ T.add(getWelcomeLetterLink(-1,topicID,"X"),5,row); } row++; } } return T; }
1,109,154
public PresentationObject getTopicsOverView(IWContext iwc){ Table T = new Table(); int row = 1; T.add(getTopicLink(-1,iwrb.getLocalizedString("new_topic","New topic")),1,row); row++; T.add(tf.format(iwrb.getLocalizedString("name","Name"),tf.HEADER),1,row); T.add(tf.format(iwrb.getLocalizedString("category","Category"),tf.HEADER),2,row); T.add(tf.format(iwrb.getLocalizedString("mail_server","Mail server"),tf.HEADER),3,row); T.add(tf.format(iwrb.getLocalizedString("subscribers","Subscribers"),tf.HEADER),4,row); T.add(tf.format(iwrb.getLocalizedString("welcome","Welcome"),tf.HEADER),5,row); row++; if(!topics.isEmpty()){ Iterator iter = topics.values().iterator(); EmailTopic topic; ICCategory category; EmailAccount account; EmailLetter welcome; Collection welcomes; Collection accounts; int emailCount; int topicID; while(iter.hasNext()){ topic = (EmailTopic) iter.next(); topicID = topic.getIdentifier().intValue(); T.add(getTopicLink(topicID,topic.getName()),1,row); category = (ICCategory) categories.get(Integer.toString(topic.getCategoryId())); T.add(tf.format(category.getName()),2,row); accounts = MailFinder.getInstance().getTopicAccounts(topicID,MailProtocol.SMTP); if(accounts!=null && !accounts.isEmpty()){ account = (EmailAccount) accounts.iterator().next(); T.add(getAccountLink(topicID,Integer.parseInt( account.toString()),account.getHost()),3,row); } else{ T.add(getAccountLink(topicID,-1,"X"),3,row); } emailCount = MailFinder.getInstance().getListEmailsCount(topic.getListId()); T.add((getSubscribersLink(topicID,String.valueOf(emailCount))),4,row); welcomes = MailFinder.getInstance().getEmailLetters(topicID,MailLetter.TYPE_SUBSCRIPTION); if(welcomes!=null && !welcomes.isEmpty()){ welcome = (MailLetter) welcomes.iterator().next(); T.add(getWelcomeLetterLink(Integer.parseInt(welcome.toString()),topicID,welcome.getSubject()),5,row); //T.add(tf.format(welcome.getSubject()),5,row); } else{ T.add(getWelcomeLetterLink(-1,topicID,"X"),5,row); } row++; } } return T; }
public PresentationObject getTopicsOverView(IWContext iwc){ Table T = new Table(); int row = 1; T.add(getTopicLink(-1,iwrb.getLocalizedString("new_topic","New topic")),1,row); row++; T.add(tf.format(iwrb.getLocalizedString("name","Name"),tf.HEADER),1,row); T.add(tf.format(iwrb.getLocalizedString("category","Category"),tf.HEADER),2,row); T.add(tf.format(iwrb.getLocalizedString("mail_server","Mail server"),tf.HEADER),3,row); T.add(tf.format(iwrb.getLocalizedString("subscribers","Subscribers"),tf.HEADER),4,row); T.add(tf.format(iwrb.getLocalizedString("welcome","Welcome"),tf.HEADER),5,row); row++; if(!topics.isEmpty()){ Iterator iter = topics.values().iterator(); EmailTopic topic; ICCategory category; EmailAccount account; EmailLetter welcome; Collection welcomes; Collection accounts; int emailCount; int topicID; while(iter.hasNext()){ topic = (EmailTopic) iter.next(); topicID = topic.getIdentifier().intValue(); T.add(getTopicLink(topicID,topic.getName()),1,row); category = (ICCategory) categories.get(Integer.toString(topic.getCategoryId())); T.add(tf.format(category.getName()),2,row); accounts = MailFinder.getInstance().getTopicAccounts(topicID,MailProtocol.SMTP); if(accounts!=null && !accounts.isEmpty()){ account = (EmailAccount) accounts.iterator().next(); T.add(getAccountLink(topicID,Integer.parseInt( account.toString()),account.getHost()),3,row); } else{ T.add(getAccountLink(topicID,-1,"X"),3,row); } emailCount = MailFinder.getInstance().getListEmailsCount(topic.getListId()); T.add((getSubscribersLink(topicID,String.valueOf(emailCount))),4,row); welcomes = MailFinder.getInstance().getEmailLetters(topicID,MailLetter.TYPE_SUBSCRIPTION); if(welcomes!=null && !welcomes.isEmpty()){ welcome = (MailLetter) welcomes.iterator().next(); T.add(getWelcomeLetterLink(welcome.getIdentifier().intValue()),topicID,welcome.getSubject()),5,row); //T.add(tf.format(welcome.getSubject()),5,row); } else{ T.add(getWelcomeLetterLink(-1,topicID,"X"),5,row); } row++; } } return T; }
1,109,155
public void mouseClicked(MouseEvent evt) { // TODO Auto-generated method stub Object obj = evt.getSource(); if (evt.getClickCount() == 2) { if ( obj instanceof JTable ) { JTable t = (JTable)obj; SQLColumn col = (SQLColumn)t.getValueAt(t.getSelectedRow(),4); Set<SQLTable> tables = new HashSet<SQLTable>(); for (int i =0; i < t.getRowCount(); i++){ tables.add((SQLTable)t.getValueAt(i,3)); } profilePanel.setTables(new ArrayList(tables)); profilePanel.getTableSelector().setSelectedItem(col.getParentTable()); profilePanel.getColumnSelector().setSelectedValue(col,true); tabPane.setSelectedIndex(1); } } }
public void mouseClicked(MouseEvent evt) { // TODO Auto-generated method stub Object obj = evt.getSource(); if (evt.getClickCount() == 2) { if ( obj instanceof JTable ) { JTable t = (JTable)obj; SQLColumn col = (SQLColumn)t.getValueAt(t.getSelectedRow(),4); Set<SQLTable> tables = new HashSet<SQLTable>(); for (int i =0; i < t.getRowCount(); i++){ tables.add((SQLTable)t.getValueAt(i,3)); } profilePanel.setTables(new ArrayList(tables)); profilePanel.getTableSelector().setSelectedItem(col.getParentTable()); profilePanel.getColumnSelector().setSelectedValue(col,true); tabPane.setSelectedIndex(1); } } }
1,109,156
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i, viewTable.convertColumnIndexToView( ProfileColumn.valueOf("TABLE").ordinal())); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
1,109,157
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
1,109,158
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, viewTable.convertColumnIndexToView( ProfileColumn.valueOf("COLUMN").ordinal())); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
1,109,159
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); final CommonCloseAction commonCloseAction = new CommonCloseAction(d); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); commonCloseAction.actionPerformed(evt); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, commonCloseAction); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); // XXX This should be its own Action class? new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
1,109,160
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i, viewTable.convertColumnIndexToView( ProfileColumn.valueOf("TABLE").ordinal())); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
1,109,162
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
1,109,163
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, viewTable.convertColumnIndexToView( ProfileColumn.valueOf("COLUMN").ordinal())); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
1,109,164
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSearchDecorator searchDecorator = new TableModelSearchDecorator(tm); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(searchDecorator); final ProfileTable viewTable = new ProfileTable(tableModelSortDecorator); searchDecorator.setTableTextConverter(viewTable); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths ((ProfileTable) viewTable).initColumnSizes(); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); JLabel searchLabel = new JLabel("Search:"); JTextField searchField = new JTextField(searchDecorator.getDoc(),"",25); searchField.setEditable(true); JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); searchPanel.add(searchLabel); searchPanel.add(searchField); tableViewPane.add(searchPanel,BorderLayout.NORTH); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new SaveProfileAction(d,viewTable,profileManager)); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
1,109,165
public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i, viewTable.convertColumnIndexToView( ProfileColumn.valueOf("TABLE").ordinal())); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
1,109,167
public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } }
public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } }
1,109,168
public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } }
public void actionPerformed(ActionEvent e) { while ( viewTable.getRowCount() > 0 ) { SQLColumn col = (SQLColumn) viewTable.getValueAt(0, viewTable.convertColumnIndexToView( ProfileColumn.valueOf("COLUMN").ordinal())); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete row of:" + col.getName(), e1); } } }
1,109,169
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } 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,V_BORDER,this); // not sure if this is an imageObserver, however 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; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)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) { 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).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); 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); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } 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 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(printDPrimeValues){ 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); } } } } //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); //see if the user has right-clicked to popup some marker info if(popupExists){ //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); } } 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 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); } }
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } 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); // not sure if this is an imageObserver, however 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; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)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) { 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).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); 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); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } 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 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(printDPrimeValues){ 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); } } } } //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); //see if the user has right-clicked to popup some marker info if(popupExists){ //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); } } 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 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); } }
1,109,171
public String getColumnName(int column) { if ( column == 0 ) { return "Count"; } else if ( column == 1 ) { return "Value"; } else { throw new IllegalStateException("Unknown Column Index:"+column); } }
public String getColumnName(int column) { if ( column == 0 ) { return COUNT; } else if ( column == 1 ) { return "Value"; } else { throw new IllegalStateException("Unknown Column Index:"+column); } }
1,109,172
public String getColumnName(int column) { if ( column == 0 ) { return "Count"; } else if ( column == 1 ) { return "Value"; } else { throw new IllegalStateException("Unknown Column Index:"+column); } }
public String getColumnName(int column) { if ( column == 0 ) { return "Count"; } else if ( column == 1 ) { return VALUE; } else { throw new IllegalStateException("Unknown Column Index:"+column); } }
1,109,173
public void doTag(XMLOutput output) throws JellyTagException { int idx = name.indexOf(':'); final String localName = (idx >= 0) ? name.substring(idx + 1) : name; outputAttributes = false; XMLOutput newOutput = new XMLOutput(output) { // add an initialize hook to the core content-generating methods public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { initialize(); super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { initialize(); super.endElement(uri, localName, qName); } public void characters(char ch[], int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); } public void objectData(Object object) throws SAXException { initialize(); super.objectData( object ); } public void processingInstruction(String target, String data) throws SAXException { initialize(); super.processingInstruction(target, data); } /** * Ensure that the outer start element is generated * before any content is output */ protected void initialize() throws SAXException { if (!outputAttributes) { super.startElement(namespace, localName, name, attributes); outputAttributes = true; } } }; invokeBody(newOutput); try { if (!outputAttributes) { output.startElement(namespace, localName, name, attributes); outputAttributes = true; } output.endElement(namespace, localName, name); attributes.clear(); } catch (SAXException e) { throw new JellyTagException(e); } }
public void doTag(XMLOutput output) throws JellyTagException { int idx = name.indexOf(':'); final String localName = (idx >= 0) ? name.substring(idx + 1) : name; outputAttributes = false; XMLOutput newOutput = new XMLOutput(output) { // add an initialize hook to the core content-generating methods public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { initialize(); super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { initialize(); super.endElement(uri, localName, qName); } public void characters(char[] ch, int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); } public void objectData(Object object) throws SAXException { initialize(); super.objectData( object ); } public void processingInstruction(String target, String data) throws SAXException { initialize(); super.processingInstruction(target, data); } /** * Ensure that the outer start element is generated * before any content is output */ protected void initialize() throws SAXException { if (!outputAttributes) { super.startElement(namespace, localName, name, attributes); outputAttributes = true; } } }; invokeBody(newOutput); try { if (!outputAttributes) { output.startElement(namespace, localName, name, attributes); outputAttributes = true; } output.endElement(namespace, localName, name); attributes.clear(); } catch (SAXException e) { throw new JellyTagException(e); } }
1,109,174
public void doTag(XMLOutput output) throws JellyTagException { int idx = name.indexOf(':'); final String localName = (idx >= 0) ? name.substring(idx + 1) : name; outputAttributes = false; XMLOutput newOutput = new XMLOutput(output) { // add an initialize hook to the core content-generating methods public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { initialize(); super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { initialize(); super.endElement(uri, localName, qName); } public void characters(char ch[], int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); } public void objectData(Object object) throws SAXException { initialize(); super.objectData( object ); } public void processingInstruction(String target, String data) throws SAXException { initialize(); super.processingInstruction(target, data); } /** * Ensure that the outer start element is generated * before any content is output */ protected void initialize() throws SAXException { if (!outputAttributes) { super.startElement(namespace, localName, name, attributes); outputAttributes = true; } } }; invokeBody(newOutput); try { if (!outputAttributes) { output.startElement(namespace, localName, name, attributes); outputAttributes = true; } output.endElement(namespace, localName, name); attributes.clear(); } catch (SAXException e) { throw new JellyTagException(e); } }
public void doTag(XMLOutput output) throws JellyTagException { int idx = name.indexOf(':'); final String localName = (idx >= 0) ? name.substring(idx + 1) : name; outputAttributes = false; XMLOutput newOutput = new XMLOutput(output) { // add an initialize hook to the core content-generating methods public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { initialize(); super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { initialize(); super.endElement(uri, localName, qName); } public void characters(char ch[], int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); } public void objectData(Object object) throws SAXException { initialize(); super.objectData( object ); } public void processingInstruction(String target, String data) throws SAXException { initialize(); super.processingInstruction(target, data); } /** * Ensure that the outer start element is generated * before any content is output */ protected void initialize() throws SAXException { if (!outputAttributes) { super.startElement(namespace, localName, name, attributes); outputAttributes = true; } } }; invokeBody(newOutput); try { if (!outputAttributes) { output.startElement(namespace, localName, name, attributes); outputAttributes = true; } output.endElement(namespace, localName, name); attributes.clear(); } catch (SAXException e) { throw new JellyTagException(e); } }
1,109,175
public void doTag(XMLOutput output) throws JellyTagException { int idx = name.indexOf(':'); final String localName = (idx >= 0) ? name.substring(idx + 1) : name; outputAttributes = false; XMLOutput newOutput = new XMLOutput(output) { // add an initialize hook to the core content-generating methods public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { initialize(); super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { initialize(); super.endElement(uri, localName, qName); } public void characters(char ch[], int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); } public void objectData(Object object) throws SAXException { initialize(); super.objectData( object ); } public void processingInstruction(String target, String data) throws SAXException { initialize(); super.processingInstruction(target, data); } /** * Ensure that the outer start element is generated * before any content is output */ protected void initialize() throws SAXException { if (!outputAttributes) { super.startElement(namespace, localName, name, attributes); outputAttributes = true; } } }; invokeBody(newOutput); try { if (!outputAttributes) { output.startElement(namespace, localName, name, attributes); outputAttributes = true; } output.endElement(namespace, localName, name); attributes.clear(); } catch (SAXException e) { throw new JellyTagException(e); } }
public void doTag(XMLOutput output) throws JellyTagException { int idx = name.indexOf(':'); final String localName = (idx >= 0) ? name.substring(idx + 1) : name; outputAttributes = false; XMLOutput newOutput = new XMLOutput(output) { // add an initialize hook to the core content-generating methods public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { initialize(); super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { initialize(); super.endElement(uri, localName, qName); } public void characters(char ch[], int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); } public void objectData(Object object) throws SAXException { initialize(); super.objectData( object ); } public void processingInstruction(String target, String data) throws SAXException { initialize(); super.processingInstruction(target, data); } /** * Ensure that the outer start element is generated * before any content is output. */ protected void initialize() throws SAXException { if (!outputAttributes) { super.startElement(namespace, localName, name, attributes); outputAttributes = true; } } }; invokeBody(newOutput); try { if (!outputAttributes) { output.startElement(namespace, localName, name, attributes); outputAttributes = true; } output.endElement(namespace, localName, name); attributes.clear(); } catch (SAXException e) { throw new JellyTagException(e); } }
1,109,176
public void characters(char ch[], int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); }
public void characters(char[] ch, int start, int length) throws SAXException { initialize(); super.characters(ch, start, length); }
1,109,177
public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); }
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { initialize(); super.ignorableWhitespace(ch, start, length); }
1,109,178
public void setAttributeValue( String name, String value ) throws JellyTagException { if (outputAttributes) { throw new JellyTagException( "Cannot set the value of attribute: " + name + " as we have already output the startElement() SAX event" ); } // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value); } }
public void setAttributeValue(String name, String value, String uri) throws JellyTagException { if (outputAttributes) { throw new JellyTagException( "Cannot set the value of attribute: " + name + " as we have already output the startElement() SAX event" ); } // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value); } }
1,109,179
public void setAttributeValue( String name, String value ) throws JellyTagException { if (outputAttributes) { throw new JellyTagException( "Cannot set the value of attribute: " + name + " as we have already output the startElement() SAX event" ); } // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value); } }
public void setAttributeValue( String name, String value ) throws JellyTagException { if (outputAttributes) { throw new JellyTagException( "Cannot set the value of attribute: " + name + " as we have already output the startElement() SAX event" ); } // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int idx = name.indexOf(':'); final String localName = (idx >= 0) ? name.substring(idx + 1) : name; final String nsUri = (uri != null) ? uri : ""; int index = attributes.getIndex(nsUri, localName); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value); } }
1,109,180
public void setAttributeValue( String name, String value ) throws JellyTagException { if (outputAttributes) { throw new JellyTagException( "Cannot set the value of attribute: " + name + " as we have already output the startElement() SAX event" ); } // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value); } }
public void setAttributeValue( String name, String value ) throws JellyTagException { if (outputAttributes) { throw new JellyTagException( "Cannot set the value of attribute: " + name + " as we have already output the startElement() SAX event" ); } // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute(nsUri, localName, name, "CDATA", value); } }
1,109,181
public void actionPerformed(ActionEvent e) { List items = pp.getSelectedItems(); Iterator it = items.iterator(); while (it.hasNext()) { PlayPenComponent c = (PlayPenComponent) it.next(); pp.contentPane.remove(c); pp.contentPane.add(c, 0); } pp.repaint(); }
public void actionPerformed(ActionEvent e) { List items = pp.getSelectedItems(); Iterator it = items.iterator(); while (it.hasNext()) { PlayPenComponent c = (PlayPenComponent) it.next(); pp.contentPane.remove(c); if (c instanceof Relationship) { pp.contentPane.add(c,pp.contentPane.getFirstRelationIndex()); } else { pp.contentPane.add(c, 0); } } pp.repaint(); }
1,109,182
public void dbChildrenInserted(SQLObjectEvent e) { logger.debug("SQLObject children got inserted: "+e); boolean fireEvent = false; SQLObject[] c = e.getChildren(); for (int i = 0; i < c.length; i++) { try { addHierarcyListeners(c[i]); } catch (ArchitectException ex) { logger.error("Couldn't listen to added object", ex); } if (c[i] instanceof SQLTable || (c[i] instanceof SQLRelationship && (((SQLTable.Folder) e.getSource()).getType() == SQLTable.Folder.EXPORTED_KEYS))) { fireEvent = true; PlayPenComponent ppc = removedComponents.get(c[i]); if (ppc != null) { contentPane.add(ppc, contentPane.getComponentCount()); } } } if (fireEvent) { firePropertyChange("model.children", null, null); revalidate(); } }
public void dbChildrenInserted(SQLObjectEvent e) { logger.debug("SQLObject children got inserted: "+e); boolean fireEvent = false; SQLObject[] c = e.getChildren(); for (int i = 0; i < c.length; i++) { try { addHierarcyListeners(c[i]); } catch (ArchitectException ex) { logger.error("Couldn't listen to added object", ex); } if (c[i] instanceof SQLTable || (c[i] instanceof SQLRelationship && (((SQLTable.Folder) e.getSource()).getType() == SQLTable.Folder.EXPORTED_KEYS))) { fireEvent = true; PlayPenComponent ppc = removedComponents.get(c[i]); if (ppc != null) { if (ppc instanceof Relationship) { contentPane.add(ppc, contentPane.getComponentCount()); } else { contentPane.add(ppc, contentPane.getFirstRelationIndex()); } } } } if (fireEvent) { firePropertyChange("model.children", null, null); revalidate(); } }
1,109,183
public void showDbcsDialog() { final DBCSPanel dbcsPanel = new DBCSPanel(); DBCS_OkAction okAction = new DBCS_OkAction(dbcsPanel, false); dbcsPanel.setDbcs(db.getDataSource()); Action cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dbcsPanel.discardChanges(); } }; JDialog d = ArchitectPanelBuilder.createArchitectPanelDialog( dbcsPanel, ArchitectFrame.getMainInstance(), "Target Database Connection", ArchitectPanelBuilder.OK_BUTTON_LABEL, okAction, cancelAction); okAction.setConnectionDialog(d); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); dbcsDialog = d; dbcsDialog.setVisible(true); }
public void showDbcsDialog() { final DBCSPanel dbcsPanel = new DBCSPanel(); DBCS_OkAction okAction = new DBCS_OkAction(dbcsPanel, false); Action cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dbcsPanel.discardChanges(); } }; JDialog d = ArchitectPanelBuilder.createArchitectPanelDialog( dbcsPanel, ArchitectFrame.getMainInstance(), "Target Database Connection", ArchitectPanelBuilder.OK_BUTTON_LABEL, okAction, cancelAction); okAction.setConnectionDialog(d); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); dbcsDialog = d; dbcsDialog.setVisible(true); }
1,109,184
public PostageException(String message, Throwable cause) { super(message, cause); }
public PostageException(String message, Throwable cause) { super(message, cause); }
1,109,185
public void actionPerformed( ActionEvent ev ) { try { Collection selectedPhotos = view.getSelection(); Iterator iter = selectedPhotos.iterator(); while ( iter.hasNext() ) { PhotoInfo photo = (PhotoInfo) iter.next(); JFrame frame = new JFrame( "Photo" ); final JAIPhotoViewer viewer = new JAIPhotoViewer(); frame.getContentPane().add( viewer, BorderLayout.CENTER ); frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); // This is a WAR for a memory management problem. For // some reason the frame and objects owned by it seem // not to be garbage collected. So we free the large // image buffers to avoid massive memory leak. frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { viewer.setPhoto( null ); } } ); viewer.setPhoto( photo ); frame.pack(); frame.setVisible( true ); } } catch ( Throwable e ) { System.err.println( "Out of memory error" ); log.warn( e ); e.printStackTrace(); } }
public void actionPerformed( ActionEvent ev ) { try { Collection selectedPhotos = view.getSelection(); if ( selectedPhotos.size() > 1 ) { int n = JOptionPane.showConfirmDialog( parentFrame, "You have selected " + selectedPhotos.size() + " photos\n" + "Are you sure that you want to\ndisplay all of them at once?", "Open multiple photos", JOptionPane.YES_NO_OPTION ); if ( n != JOptionPane.YES_OPTION ) { return; } } Cursor oldCursor = c.getCursor(); c.setCursor( new Cursor( Cursor.WAIT_CURSOR ) ); Iterator iter = selectedPhotos.iterator(); while ( iter.hasNext() ) { PhotoInfo photo = (PhotoInfo) iter.next(); JFrame frame = new JFrame( "Photo" ); final JAIPhotoViewer viewer = new JAIPhotoViewer(); frame.getContentPane().add( viewer, BorderLayout.CENTER ); frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); // This is a WAR for a memory management problem. For // some reason the frame and objects owned by it seem // not to be garbage collected. So we free the large // image buffers to avoid massive memory leak. frame.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { viewer.setPhoto( null ); } } ); viewer.setPhoto( photo ); frame.pack(); frame.setVisible( true ); } } catch ( Throwable e ) { System.err.println( "Out of memory error" ); log.warn( e ); e.printStackTrace(); } }
1,109,186
public JAIPhotoViewer() { super(); createUI(); addComponentListener( this ); }
public JAIPhotoViewer() { super(); createUI(); }
1,109,188
public void doTag(XMLOutput output) throws Exception { String message = getBodyText(); Object expectedValue = expected.evaluate(context); Object actualValue = actual.evaluate(context); if (expectedValue == null && actualValue == null) { return; } if (actualValue != null && expectedValue.equals(actualValue)) { return; } String expressions = "\nExpected expression: " + expected + "\nActual expression: " + actual; failNotEquals(message, expectedValue, actualValue, expressions); }
public void doTag(XMLOutput output) throws Exception { String message = getBodyText(); Object expectedValue = expected.evaluate(context); Object actualValue = actual.evaluate(context); if (expectedValue == null && actualValue == null) { return; } if (actualValue != null && expectedValue.equals(actualValue)) { return; } String expressions = "\nExpected expression: " + expected.getExpressionText() + "\nActual expression: " + actual.getExpressionText(); failNotEquals(message, expectedValue, actualValue, expressions); }
1,109,189
abstract void dumpTree(Appendable app, int indentLevel) throws IOException;
public void dumpTree(Appendable app) throws IOException { dumpTree(app, 0); }
1,109,191
public TagScript createTagScript(final String name, final Attributes attributes) throws Exception { return new TagScript( new TagFactory() { public Tag createTag(String name, Attributes attributes) throws Exception { Tag answer = DynamicTagLibrary.this.createTag(name, attributes); // delegate to my parent instead if ( answer == null && parent != null ) { return parent.createTag(name, attributes); } return answer; } } ); }
public TagScript createTagScript(final String name, final Attributes attributes) throws Exception { return new TagScript( new TagFactory() { public Tag createTag(String name, Attributes attributes) throws Exception { Tag answer = DynamicTagLibrary.this.createTag(name, attributes); // delegate to my parent instead if ( answer == null && parent != null ) { return parent.createTag(name, attributes); } return answer; } } ); }
1,109,192
public Tag createTag(String name, Attributes attributes) throws Exception { Tag answer = DynamicTagLibrary.this.createTag(name, attributes); // delegate to my parent instead if ( answer == null && parent != null ) { return parent.createTag(name, attributes); } return answer; }
public Tag createTag(String name, Attributes attributes) throws Exception { Tag answer = DynamicTagLibrary.this.createTag(name, attributes); // delegate to my parent instead if ( answer == null && parent != null ) { return parent.createTag(name, attributes); } return answer; }
1,109,193
public DynamicTag(Script template) { this.template = template; }
public DynamicTag(Script template) { this.template = template; }
1,109,194
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; } if (zoomLevel == 0){ printDetails = true; } else{ printDetails = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); if (size.height < pref.height){ setSize(pref); } //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.setColor(BG_GREY); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.black); 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.getMarker(last).getPosition() - Chromosome.getMarker(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); } }
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; } if (zoomLevel == 0){ printDetails = true; } else{ printDetails = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); if (size.height < pref.height){ setSize(pref); } //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.setColor(BG_GREY); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.black); 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.getMarker(last).getPosition() - Chromosome.getMarker(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); } }
1,109,195
public boolean addDriverJar(String fullPath) { return driverJarList.add(fullPath); }
public boolean addDriverJar(String fullPath) { return driverJarList.add(fullPath); }
1,109,196