rem
stringlengths
0
477k
add
stringlengths
0
313k
context
stringlengths
6
599k
testDir = new File( "c:\\java\\photovault\\tests\\images\\photovault\\image\\ImageXform" );
testDir = new File( refImgDir, "photovault/image/ImageXform" );
public void setUp() { File f = new File( "c:\\java\\photovault\\testfiles\\test1.jpg" ); try { source = ImageIO.read( f ); } catch ( IOException e ) { System.err.println( "Error reading image: " + e.getMessage() ); return; } testDir = new File( "c:\\java\\photovault\\tests\\images\\photovault\\image\\ImageXform" ); }
fakeHaplos[j][k] = new Haplotype(new int[0],haplotypes[j][k].getPercentage(),null);
fakeHaplos[j][k] = new Haplotype(haplotypes[j][k].getGeno(),haplotypes[j][k].getPercentage(), haplotypes[j][k].getMarkers());
public void doPermutations() { stopProcessing = false; Vector curResults = null; Haplotype[][] haplotypes = new Haplotype[testSet.getHaplotypeAssociationResults().size()][]; Iterator hitr = testSet.getHaplotypeAssociationResults().iterator(); int count = 0; while (hitr.hasNext()){ haplotypes[count] = ((HaplotypeAssociationResult)hitr.next()).getHaps(); count++; } Vector snpSet = new Vector(); Iterator sitr = testSet.getFilteredResults().iterator(); while (sitr.hasNext()){ Object o = sitr.next(); if (o instanceof MarkerAssociationResult){ SNP snp = ((MarkerAssociationResult)o).getSnp(); snpSet.add(snp); } } //we need to make fake Haplotype objects so that we can use the getcounts() and getChiSq() methods of //AssociationResult. kludgetastic! Haplotype[][] fakeHaplos; if(haplotypes != null) { fakeHaplos = new Haplotype[haplotypes.length][]; for(int j=0;j<haplotypes.length;j++) { fakeHaplos[j] = new Haplotype[haplotypes[j].length]; for(int k=0;k<haplotypes[j].length;k++) { fakeHaplos[j][k] = new Haplotype(new int[0],haplotypes[j][k].getPercentage(),null); } } } else { fakeHaplos = new Haplotype[0][0]; } //need to use the same affected status for marker and haplotype association tests in case control, //so affectedStatus stores the shuffled affected status Vector affectedStatus = null; //need to use the same coin toss for marker and haplotype association tests in trio tdt, //so permuteInd stores whether each individual is permuted Vector permuteInd = null; permutationsPerformed = 0; bestExceededCount = 0; double[] chiSqs = new double[permutationCount]; permBestOverallChiSq = 0; //start the permuting! for(int i=0;i<permutationCount; i++) { //this variable gets set by the thread we're running if it wants us to stop if(stopProcessing) { break; } //begin single marker association test if (Options.getAssocTest() == ASSOC_TRIO){ try { permuteInd = new Vector(); for(int j =0;j<pedFile.getAllIndividuals().size();j++) { if(Math.random() < .5) { permuteInd.add(new Boolean(true)); } else { permuteInd.add(new Boolean(false)); } } curResults = new AssociationTestSet(pedFile, permuteInd, snpSet).getMarkerAssociationResults(); } catch(PedFileException pfe) { } }else if (Options.getAssocTest() == ASSOC_CC){ Vector indList = pedFile.getUnrelatedIndividuals(); affectedStatus = new Vector(); for(int j=0;j<indList.size();j++) { affectedStatus.add(new Integer(((Individual)indList.elementAt(j)).getAffectedStatus())); } Collections.shuffle(affectedStatus); try{ curResults = new AssociationTestSet(pedFile,affectedStatus, snpSet).getMarkerAssociationResults(); }catch (PedFileException pfe){ } } //end of marker association test //begin haplotype association test if(Options.getAssocTest() == ASSOC_TRIO) { for(int j=0;j<fakeHaplos.length;j++) { EM curEM = (EM) theEMs.get(j); curEM.doAssociationTests(null,permuteInd); for(int k=0;k<fakeHaplos[j].length;k++) { fakeHaplos[j][k].setTransCount(curEM.getTransCount(k)); fakeHaplos[j][k].setUntransCount(curEM.getUntransCount(k)); } } } else if(Options.getAssocTest() == ASSOC_CC) { for(int j=0;j<fakeHaplos.length;j++) { EM curEM = (EM) theEMs.get(j); curEM.doAssociationTests(affectedStatus,null); for(int k=0;k<fakeHaplos[j].length;k++) { fakeHaplos[j][k].setCaseCount(curEM.getCaseCount(k)); fakeHaplos[j][k].setControlCount(curEM.getControlCount(k)); } } } if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) { AssociationTestSet ats = new AssociationTestSet(fakeHaplos, null); curResults.addAll(ats.getResults()); } //end of haplotype association test //find the best chi square from all the tests double tempBestChiSquare = 0; for(int j=0; j<curResults.size();j++) { AssociationResult tempResult = (AssociationResult) curResults.elementAt(j); for (int k = 0; k < tempResult.getAlleleCount(); k++){ if(tempResult.getChiSquare(k) > tempBestChiSquare) { tempBestChiSquare = tempResult.getChiSquare(k); } } } chiSqs[i] = tempBestChiSquare; if (chiSqs[i] >= bestObsChiSq){ bestExceededCount++; } if(chiSqs[i] > permBestOverallChiSq){ permBestOverallChiSq = chiSqs[i]; } permutationsPerformed++; } permBestChiSq = new double[permutationsPerformed]; for (int i = 0; i < permutationsPerformed; i++){ permBestChiSq[i] = chiSqs[i]; } Arrays.sort(permBestChiSq); }
AssociationTestSet ats = new AssociationTestSet(fakeHaplos, null);
AssociationTestSet ats = null; if (testSet.getFilterAlleles() == null){ ats = new AssociationTestSet(fakeHaplos, null); }else{ try{ ats = new AssociationTestSet(fakeHaplos,null,testSet.getFilterAlleles()); }catch (HaploViewException hve){ } }
public void doPermutations() { stopProcessing = false; Vector curResults = null; Haplotype[][] haplotypes = new Haplotype[testSet.getHaplotypeAssociationResults().size()][]; Iterator hitr = testSet.getHaplotypeAssociationResults().iterator(); int count = 0; while (hitr.hasNext()){ haplotypes[count] = ((HaplotypeAssociationResult)hitr.next()).getHaps(); count++; } Vector snpSet = new Vector(); Iterator sitr = testSet.getFilteredResults().iterator(); while (sitr.hasNext()){ Object o = sitr.next(); if (o instanceof MarkerAssociationResult){ SNP snp = ((MarkerAssociationResult)o).getSnp(); snpSet.add(snp); } } //we need to make fake Haplotype objects so that we can use the getcounts() and getChiSq() methods of //AssociationResult. kludgetastic! Haplotype[][] fakeHaplos; if(haplotypes != null) { fakeHaplos = new Haplotype[haplotypes.length][]; for(int j=0;j<haplotypes.length;j++) { fakeHaplos[j] = new Haplotype[haplotypes[j].length]; for(int k=0;k<haplotypes[j].length;k++) { fakeHaplos[j][k] = new Haplotype(new int[0],haplotypes[j][k].getPercentage(),null); } } } else { fakeHaplos = new Haplotype[0][0]; } //need to use the same affected status for marker and haplotype association tests in case control, //so affectedStatus stores the shuffled affected status Vector affectedStatus = null; //need to use the same coin toss for marker and haplotype association tests in trio tdt, //so permuteInd stores whether each individual is permuted Vector permuteInd = null; permutationsPerformed = 0; bestExceededCount = 0; double[] chiSqs = new double[permutationCount]; permBestOverallChiSq = 0; //start the permuting! for(int i=0;i<permutationCount; i++) { //this variable gets set by the thread we're running if it wants us to stop if(stopProcessing) { break; } //begin single marker association test if (Options.getAssocTest() == ASSOC_TRIO){ try { permuteInd = new Vector(); for(int j =0;j<pedFile.getAllIndividuals().size();j++) { if(Math.random() < .5) { permuteInd.add(new Boolean(true)); } else { permuteInd.add(new Boolean(false)); } } curResults = new AssociationTestSet(pedFile, permuteInd, snpSet).getMarkerAssociationResults(); } catch(PedFileException pfe) { } }else if (Options.getAssocTest() == ASSOC_CC){ Vector indList = pedFile.getUnrelatedIndividuals(); affectedStatus = new Vector(); for(int j=0;j<indList.size();j++) { affectedStatus.add(new Integer(((Individual)indList.elementAt(j)).getAffectedStatus())); } Collections.shuffle(affectedStatus); try{ curResults = new AssociationTestSet(pedFile,affectedStatus, snpSet).getMarkerAssociationResults(); }catch (PedFileException pfe){ } } //end of marker association test //begin haplotype association test if(Options.getAssocTest() == ASSOC_TRIO) { for(int j=0;j<fakeHaplos.length;j++) { EM curEM = (EM) theEMs.get(j); curEM.doAssociationTests(null,permuteInd); for(int k=0;k<fakeHaplos[j].length;k++) { fakeHaplos[j][k].setTransCount(curEM.getTransCount(k)); fakeHaplos[j][k].setUntransCount(curEM.getUntransCount(k)); } } } else if(Options.getAssocTest() == ASSOC_CC) { for(int j=0;j<fakeHaplos.length;j++) { EM curEM = (EM) theEMs.get(j); curEM.doAssociationTests(affectedStatus,null); for(int k=0;k<fakeHaplos[j].length;k++) { fakeHaplos[j][k].setCaseCount(curEM.getCaseCount(k)); fakeHaplos[j][k].setControlCount(curEM.getControlCount(k)); } } } if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) { AssociationTestSet ats = new AssociationTestSet(fakeHaplos, null); curResults.addAll(ats.getResults()); } //end of haplotype association test //find the best chi square from all the tests double tempBestChiSquare = 0; for(int j=0; j<curResults.size();j++) { AssociationResult tempResult = (AssociationResult) curResults.elementAt(j); for (int k = 0; k < tempResult.getAlleleCount(); k++){ if(tempResult.getChiSquare(k) > tempBestChiSquare) { tempBestChiSquare = tempResult.getChiSquare(k); } } } chiSqs[i] = tempBestChiSquare; if (chiSqs[i] >= bestObsChiSq){ bestExceededCount++; } if(chiSqs[i] > permBestOverallChiSq){ permBestOverallChiSq = chiSqs[i]; } permutationsPerformed++; } permBestChiSq = new double[permutationsPerformed]; for (int i = 0; i < permutationsPerformed; i++){ permBestChiSq[i] = chiSqs[i]; } Arrays.sort(permBestChiSq); }
public BufferedImage export(int start, int stop){
public BufferedImage export(int start, int stop, boolean compress){
public BufferedImage export(int start, int stop){ forExport = true; exportStart = start; if (exportStart < 0){ exportStart = 0; } exportStop = stop; if (exportStop > theData.filteredDPrimeTable.length){ exportStop = theData.filteredDPrimeTable.length; } Dimension pref = getPreferredSize(); BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); forExport = false; return i; }
boxSize = startBS; boxRadius = startBR; printDetails = startPD;
public BufferedImage export(int start, int stop){ forExport = true; exportStart = start; if (exportStart < 0){ exportStart = 0; } exportStop = stop; if (exportStop > theData.filteredDPrimeTable.length){ exportStop = theData.filteredDPrimeTable.length; } Dimension pref = getPreferredSize(); BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); forExport = false; return i; }
g.setFont(markerNameFont); FontMetrics fm = g.getFontMetrics(); if (printDetails){ blockDispHeight = boxSize/3 + fm.getAscent(); }else{ blockDispHeight = boxSize/3;
if (g != null){ g.setFont(markerNameFont); FontMetrics fm = g.getFontMetrics(); if (printDetails){ blockDispHeight = boxSize/3 + fm.getAscent(); }else{ blockDispHeight = boxSize/3; }
public Dimension getPreferredSize() { //loop through table to find deepest non-null comparison PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; int upLim, loLim; if (forExport){ loLim = exportStart; upLim = exportStop; }else{ loLim = 0; upLim = dPrimeTable.length; } int count = 0; for (int x = loLim; x < upLim-1; x++){ for (int y = x+1; y < upLim; y++){ if (dPrimeTable[x][y] != null){ if (count < y-x){ count = y-x; } } } } //add one so we don't clip bottom box count ++; Graphics g = this.getGraphics(); g.setFont(markerNameFont); FontMetrics fm = g.getFontMetrics(); if (printDetails){ blockDispHeight = boxSize/3 + fm.getAscent(); }else{ blockDispHeight = boxSize/3; } int high = 2*V_BORDER + count*boxSize/2 + blockDispHeight; chartSize = new Dimension(2*H_BORDER + boxSize*(upLim-1),high); //this dimension is just the area taken up by the dprime chart //it is used in drawing the worldmap if (theData.infoKnown){ infoHeight = TICK_HEIGHT + TICK_BOTTOM + widestMarkerName + TEXT_GAP; high += infoHeight; }else{ infoHeight=0; } if (theData.trackExists){ //make room for analysis track at top high += TRACK_HEIGHT + TRACK_GAP; } int wide = 2*H_BORDER + boxSize*(upLim-loLim-1); Rectangle visRect = getVisibleRect(); //big datasets often scroll way offscreen in zoom-out mode //but aren't the full height of the viewport if (high < visRect.height && showWM){ high = visRect.height; } return new Dimension(wide, high); }
if (zoomLevel == 0){ printDetails = true; } else{ printDetails = false; }
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } 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.getFilteredMarker(last).getPosition() - Chromosome.getFilteredMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, left+first*boxSize-boxSize/2+TEXT_GAP, top-boxSize/3); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getWidth() < visRect.width){ //dumb bug where little datasets popup the box in the wrong place smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.length; x++){ g.drawString(displayStrings[x],popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap final int WM_BD_GAP = 1; final int WM_BD_HEIGHT = 2; final int WM_BD_TOTAL = WM_BD_HEIGHT + 2*WM_BD_GAP; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth-WM_BD_TOTAL))); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2+WM_BD_TOTAL, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < dPrimeTable.length-1; x++){ for (int y = x+1; y < dPrimeTable.length; y++){ if (dPrimeTable[x][y] == null){ continue; } double xx = (x + y)*prefBoxSize/2+wmBorder.getBorderInsets(this).left; double yy = (y - x)*prefBoxSize/2+wmBorder.getBorderInsets(this).top + WM_BD_TOTAL; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable[x][y].getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left+(int)(prefBoxSize*first), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)((last-first+1)*prefBoxSize), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
if (zoomLevel == 0){ printDetails = true; } else{ printDetails = false; }
public void zoom(int type){ int diff = type - zoomLevel; zoomLevel = type; int x=0, y=0; int oldX = getVisibleRect().x; int oldY = getVisibleRect().y; int oldWidth = getVisibleRect().width; int oldHeight = getVisibleRect().height; if (diff > 0){ //we're zooming out x = oldX /(2*diff) - oldWidth/4*diff; y = oldY /(2*diff) - oldHeight/4*diff; } else if (diff < 0 ) { //we're zooming in diff = -diff; x = oldX*2*diff + oldWidth/2*diff; y = oldY*2*diff + oldHeight/2*diff; }else{ //we didn't change the zoom so don't waste cycles return; } if (x < 0){ x = 0; } if (y < 0){ y = 0; } boxSize = BOX_SIZES[zoomLevel]; boxRadius = BOX_RADII[zoomLevel]; ((JViewport)getParent()).setViewSize(getPreferredSize()); //System.out.println(oldX + " " + x + " " + oldY + " " + y); ((JViewport)getParent()).setViewPosition(new Point(x,y)); }
txw.commit();
protected void cleanupInstances() { Criteria crit = new Criteria(); crit.addEqualTo( "instances.volumeId", volume.getName() ); Criteria dateCrit = new Criteria(); dateCrit.addIsNull( "instances.checkTime" ); Criteria cutoffDateCrit = new Criteria(); cutoffDateCrit.addLessThan( "instances.checkTime", startTime ); dateCrit.addOrCriteria( cutoffDateCrit ); crit.addAndCriteria( dateCrit ); ODMGXAWrapper txw = new ODMGXAWrapper(); Implementation odmg = ODMG.getODMGImplementation(); Transaction tx = odmg.currentTransaction(); Collection result = null; try { PersistenceBroker broker = ((HasBroker) tx).getBroker(); QueryByCriteria q = new QueryByCriteria( PhotoInfo.class, crit ); result = broker.getCollectionByQuery( q ); } catch ( Exception e ) { e.printStackTrace(); } // Now go through all the photos with stray instances Iterator photoIter = result.iterator(); while ( photoIter.hasNext() ) { PhotoInfo p = (PhotoInfo) photoIter.next(); Vector instances = p.getInstances(); for ( int i = instances.size()-1; i >= 0; i-- ) { ImageInstance inst = (ImageInstance) instances.get( i ); Date checkTime = inst.getCheckTime(); if ( inst.getVolume() == volume && (checkTime == null || checkTime.before( startTime )) ) { p.removeInstance( i ); } } } }
ImageInstance instance = (ImageInstance) instances.get( 0 );
ImageInstance instance = null; if ( instances != null && instances.size() > 0 ) { instance = (ImageInstance) instances.get( 0 ); }
public static ImageInstance retrieve( VolumeBase volume, String fname ) throws PhotoNotFoundException { String oql = "select instance from " + ImageInstance.class.getName() + " where volumeId = \"" + volume.getName() + "\" and fname = \"" + fname + "\""; List instances = null; // Get transaction context ODMGXAWrapper txw = new ODMGXAWrapper(); Implementation odmg = ODMG.getODMGImplementation(); try { OQLQuery query = odmg.newOQLQuery(); query.create( oql ); instances = (List) query.execute(); txw.commit(); } catch ( Exception e ) { txw.abort(); return null; } ImageInstance instance = (ImageInstance) instances.get( 0 ); return instance; }
tp.getModel().removeChild(idx);
tp.getModel().removeColumn(idx);
public void actionPerformed(ActionEvent evt) { Selectable invoker = pp.getSelection(); if (invoker instanceof TablePane) { TablePane tp = (TablePane) invoker; int idx; while ( (idx = tp.getSelectedColumnIndex()) >= 0) { tp.getModel().removeChild(idx); } } else { JOptionPane.showMessageDialog((JComponent) invoker, "The selected item type is not recognised"); } }
String folderName = f.getName(); if ( folderName.length() > PhotoFolder.NAME_LENGTH ) { folderName = folderName.substring( 0, PhotoFolder.NAME_LENGTH ); }
void indexDirectory( File dir, PhotoFolder folder, int startPercent, int endPercent ) { log.debug( "entry: indexDirectory " + dir.getAbsolutePath() ); /** Maintain information how many instances for the photos that were previously added to the folder is found */ HashMap photoInstanceCounts = new HashMap(); HashSet foldersNotFound = new HashSet(); if ( folder != null ) { for ( int n = 0; n < folder.getPhotoCount(); n++ ) { photoInstanceCounts.put( folder.getPhoto( n ), new Integer( 0 ) ); } for ( int n = 0; n < folder.getSubfolderCount(); n++ ) { foldersNotFound.add( folder.getSubfolder( n ) ); } } File files[] = dir.listFiles(); // Count the files int fileCount = 0; int subdirCount = 0; for ( int n = 0; n < files.length; n++ ) { if ( files[n].isDirectory() ) { subdirCount++; } else { fileCount++; } } ProgressCalculator c = new ProgressCalculator( startPercent, endPercent, fileCount, subdirCount ); int nFile = 0; int nDir = 0; for ( int n = 0; n < files.length; n++ ) { File f = files[n]; if ( f.isDirectory() ) { // Create the matching folder PhotoFolder subfolder = null; if ( folder != null ) { subfolder = findSubfolderByName( folder, f.getName() ); if ( subfolder == null ) { subfolder = PhotoFolder.create( f.getName(), folder ); newFolderCount++; } else { foldersNotFound.remove( subfolder ); } } /* Calclate the start & end percentages to use when indexing this directory. Formula goes so that we estimate that to index current dirctory completely we must index files in subDirCount+1 directories (all subdirs + current directory). So we divide endPercent - startPercent into this many steps) */ int subdirStart = c.getProgress(); nDir++; c.setProcessedSubdirs( nDir ); int subdirEnd = c.getProgress(); indexDirectory( f, subfolder, subdirStart, subdirEnd ); percentComplete = c.getProgress(); } else { if ( f.canRead() ) { currentEvent = new ExtVolIndexerEvent( this ); PhotoInfo p = indexFile( f ); if ( p != null ) { if ( photoInstanceCounts.containsKey( p ) ) { // The photo is already in this folder int refCount = ((Integer)photoInstanceCounts.get( p ) ).intValue(); photoInstanceCounts.remove( p ); photoInstanceCounts.put( p, new Integer( refCount+1 )); } else { // The photo is not yet in this folder folder.addPhoto( p ); photoInstanceCounts.put( p, new Integer( 1 )); } } nFile++; c.setProcessedFiles( nFile ); percentComplete = c.getProgress(); notifyListeners( currentEvent ); } } } /* Check if some of the photos that were in folder before were not found in this directory */ Iterator iter = photoInstanceCounts.keySet().iterator(); while ( iter.hasNext() ) { PhotoInfo p = (PhotoInfo ) iter.next(); int refCount = ((Integer)photoInstanceCounts.get( p )).intValue(); if ( refCount == 0 ) { folder.removePhoto( p ); } } // Delete folders that were not anymore found iter = foldersNotFound.iterator(); while ( iter.hasNext() ) { PhotoFolder subfolder = (PhotoFolder)iter.next(); subfolder.delete(); } }
manager.undo();
if (logger.isDebugEnabled()) { logger.debug(manager); int choice = JOptionPane.showConfirmDialog(null, "Undo manager state dumped to logger." + "\n\n" + "Proceed with undo?"); if (choice == JOptionPane.YES_OPTION) { manager.undo(); } } else { manager.undo(); }
public void actionPerformed(ActionEvent evt ) { manager.undo(); }
value = parent.findVariable( name );
value = parent.getVariable( name );
public Object getVariable(String name) { Object value = variables.get(name); if ( value == null && isInherit() ) { JellyContext parent = getParent(); if (parent != null) { value = parent.findVariable( name ); } } return value; }
config.setURL(appForm.getURL());
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ApplicationForm appForm = (ApplicationForm)actionForm; ApplicationConfig config = ApplicationConfigManager.getApplicationConfig( appForm.getApplicationId()); assert config != null; config.setName(appForm.getName()); config.setHost(appForm.getHost()); if(appForm.getPort() != null) config.setPort(new Integer(appForm.getPort())); config.setUsername(appForm.getUsername()); final String password = appForm.getPassword(); if(password != null && !password.equals(config.getPassword())){ config.setPassword(password); } ApplicationConfigManager.updateApplication(config); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Updated application "+"\""+config.getName()+"\""); return mapping.findForward(Forwards.SUCCESS); }
permTests.cat(blockTestSet);
if(blockTestSet != null) { permTests.cat(blockTestSet); }
private void processFile(String fileName, int fileType, String infoFileName){ try { HaploData textData; File OutputFile; File inputFile; AssociationTestSet customAssocSet; if(!quietMode && fileName != null){ System.out.println("Using data file: " + fileName); } inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } textData = new HaploData(); //Vector result = null; if(fileType == HAPS_FILE){ //read in haps file textData.prepareHapsInput(inputFile); } else if (fileType == PED_FILE) { //read in ped file textData.linkageToChrom(inputFile, PED_FILE); if(textData.getPedFile().isBogusParents()) { System.out.println("Error: One or more individuals in the file reference non-existent parents.\nThese references have been ignored."); } }else{ //read in hapmapfile textData.linkageToChrom(inputFile,HMP_FILE); } File infoFile = null; if (infoFileName != null){ infoFile = new File(infoFileName); } if (fileType != HAPS_FILE){ textData.prepareMarkerInput(infoFile,textData.getPedFile().getHMInfo()); }else{ textData.prepareMarkerInput(infoFile,null); } HashSet whiteListedCustomMarkers = new HashSet(); if (customAssocTestsFileName != null){ customAssocSet = new AssociationTestSet(customAssocTestsFileName); whiteListedCustomMarkers = customAssocSet.getWhitelist(); }else{ customAssocSet = null; } Hashtable snpsByName = new Hashtable(); for(int i=0;i<Chromosome.getUnfilteredSize();i++) { SNP snp = Chromosome.getUnfilteredMarker(i); snpsByName.put(snp.getName(), snp); } if(forceIncludeTags != null) { for(int i=0;i<forceIncludeTags.size();i++) { if(snpsByName.containsKey(forceIncludeTags.get(i))) { whiteListedCustomMarkers.add(snpsByName.get(forceIncludeTags.get(i))); } } } textData.setWhiteList(whiteListedCustomMarkers); boolean[] markerResults = new boolean[Chromosome.getUnfilteredSize()]; Vector result = null; if (fileType != HAPS_FILE){ result = textData.getPedFile().getResults(); //once check has been run we can filter the markers for (int i = 0; i < result.size(); i++){ if (((((MarkerResult)result.get(i)).getRating() > 0 || skipCheck) && Chromosome.getUnfilteredMarker(i).getDupStatus() != 2)){ markerResults[i] = true; }else{ markerResults[i] = false; } } }else{ //we haven't done the check (HAPS files) Arrays.fill(markerResults, true); } for (int i = 0; i < excludedMarkers.size(); i++){ int cur = ((Integer)excludedMarkers.elementAt(i)).intValue(); if (cur < 1 || cur > markerResults.length){ System.out.println("Excluded marker out of bounds: " + cur + "\nMarkers must be between 1 and N, where N is the total number of markers."); System.exit(1); }else{ markerResults[cur-1] = false; } } for(int i=0;i<Chromosome.getUnfilteredSize();i++) { if(textData.isWhiteListed(Chromosome.getUnfilteredMarker(i))) { markerResults[i] = true; } } Chromosome.doFilter(markerResults); if(!quietMode && infoFile != null){ System.out.println("Using marker information file: " + infoFile.getName()); } if(outputCheck && result != null){ CheckDataPanel cp = new CheckDataPanel(textData); cp.printTable(validateOutputFile(fileName + ".CHECK")); } Vector cust = new Vector(); AssociationTestSet blockTestSet = null; if(blockOutputType != -1){ textData.generateDPrimeTable(); Haplotype[][] haplos; Haplotype[][] filtHaplos; switch(blockOutputType){ case BLOX_GABRIEL: OutputFile = validateOutputFile(fileName + ".GABRIELblocks"); break; case BLOX_4GAM: OutputFile = validateOutputFile(fileName + ".4GAMblocks"); break; case BLOX_SPINE: OutputFile = validateOutputFile(fileName + ".SPINEblocks"); break; case BLOX_CUSTOM: OutputFile = validateOutputFile(fileName + ".CUSTblocks"); //read in the blocks file File blocksFile = new File(blockFileName); if(!quietMode) { System.out.println("Using custom blocks file " + blockFileName); } cust = textData.readBlocks(blocksFile); break; case BLOX_ALL: //handled below, so we don't do anything here OutputFile = null; break; default: OutputFile = validateOutputFile(fileName + ".GABRIELblocks"); break; } //this handles output type ALL if(blockOutputType == BLOX_ALL) { OutputFile = validateOutputFile(fileName + ".GABRIELblocks"); textData.guessBlocks(BLOX_GABRIEL); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile); }else if (!quietMode){ System.out.println("Skipping block output: no valid Gabriel blocks."); } OutputFile = validateOutputFile(fileName + ".4GAMblocks"); textData.guessBlocks(BLOX_4GAM); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile);; }else if (!quietMode){ System.out.println("Skipping block output: no valid 4 Gamete blocks."); } OutputFile = validateOutputFile(fileName + ".SPINEblocks"); textData.guessBlocks(BLOX_SPINE); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile); }else if (!quietMode){ System.out.println("Skipping block output: no valid LD Spine blocks."); } }else{ //guesses blocks based on output type determined above. textData.guessBlocks(blockOutputType, cust); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile); }else if (!quietMode){ System.out.println("Skipping block output: no valid blocks."); } } if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) { if (blockOutputType == BLOX_ALL){ System.out.println("Haplotype association results cannot be used with block output \"ALL\""); }else{ if (haplos != null){ blockTestSet = new AssociationTestSet(haplos,null); blockTestSet.saveHapsToText(validateOutputFile(fileName + ".HAPASSOC")); }else if (!quietMode){ System.out.println("Skipping block association output: no valid blocks."); } } } } if(outputDprime) { OutputFile = validateOutputFile(fileName + ".LD"); if (textData.dpTable != null){ textData.saveDprimeToText(OutputFile, TABLE_TYPE, 0, Chromosome.getSize()); }else{ textData.saveDprimeToText(OutputFile, LIVE_TYPE, 0, Chromosome.getSize()); } } if (outputPNG || outputCompressedPNG){ OutputFile = validateOutputFile(fileName + ".LD.PNG"); if (textData.dpTable == null){ textData.generateDPrimeTable(); textData.guessBlocks(BLOX_CUSTOM, new Vector()); } if (trackFileName != null){ textData.readAnalysisTrack(new File(trackFileName)); if(!quietMode) { System.out.println("Using analysis track file " + trackFileName); } } DPrimeDisplay dpd = new DPrimeDisplay(textData); BufferedImage i = dpd.export(0,Chromosome.getUnfilteredSize(),outputCompressedPNG); try{ Jimi.putImage("image/png", i, OutputFile.getAbsolutePath()); }catch(JimiException je){ System.out.println(je.getMessage()); } } AssociationTestSet markerTestSet =null; if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC){ markerTestSet = new AssociationTestSet(textData.getPedFile(),null,Chromosome.getAllMarkers()); markerTestSet.saveSNPsToText(validateOutputFile(fileName + ".ASSOC")); } if(customAssocSet != null) { if(!quietMode) { System.out.println("Using custom association test file " + customAssocTestsFileName); } try { customAssocSet.runFileTests(textData,markerTestSet.getMarkerAssociationResults()); customAssocSet.saveResultsToText(validateOutputFile(fileName + ".CUSTASSOC")); }catch(IOException ioe) { System.out.println("An error occured writing the custom association results file."); customAssocSet = null; } } if(doPermutationTest) { AssociationTestSet permTests = new AssociationTestSet(); permTests.cat(markerTestSet); permTests.cat(blockTestSet); final PermutationTestSet pts = new PermutationTestSet(permutationCount,textData.getPedFile(),customAssocSet,permTests); Thread permThread = new Thread(new Runnable() { public void run() { if (pts.isCustom()){ pts.doPermutations(PermutationTestSet.CUSTOM); }else{ pts.doPermutations(PermutationTestSet.SINGLE_PLUS_BLOCKS); } } }); permThread.start(); if(!quietMode) { System.out.println("Starting " + permutationCount + " permutation tests (each . printed represents 1% of tests completed)"); } int dotsPrinted =0; while(pts.getPermutationCount() - pts.getPermutationsPerformed() > 0) { while(( (double)pts.getPermutationsPerformed() / pts.getPermutationCount())*100 > dotsPrinted) { System.out.print("."); dotsPrinted++; } try{ Thread.sleep(100); }catch(InterruptedException ie) {} } System.out.println(); try { pts.writeResultsToFile(validateOutputFile(fileName + ".PERMUT")); } catch(IOException ioe) { System.out.println("An error occured while writing the permutation test results to file."); } } if(tagging != Tagger.NONE) { if(textData.dpTable == null) { textData.generateDPrimeTable(); } Vector snps = Chromosome.getAllMarkers(); HashSet names = new HashSet(); for (int i = 0; i < snps.size(); i++) { SNP snp = (SNP) snps.elementAt(i); names.add(snp.getName()); } HashSet filteredNames = new HashSet(); for(int i=0;i<Chromosome.getSize();i++) { filteredNames.add(Chromosome.getMarker(i).getName()); } Vector sitesToCapture = new Vector(); for(int i=0;i<Chromosome.getSize();i++) { sitesToCapture.add(Chromosome.getMarker(i)); } for (int i = 0; i < forceIncludeTags.size(); i++) { String s = (String) forceIncludeTags.elementAt(i); if(!names.contains(s)) { System.out.println("Marker " + s + " in the list of forced included tags does not appear in the marker info file."); System.exit(1); } } for (int i = 0; i < forceExcludeTags.size(); i++) { String s = (String) forceExcludeTags.elementAt(i); if(!names.contains(s)) { System.out.println("Marker " + s + " in the list of forced excluded tags does not appear in the marker info file."); System.exit(1); } } forceExcludeTags.retainAll(filteredNames); if(!quietMode) { System.out.println("Starting tagging."); } TaggerController tc = new TaggerController(textData,forceIncludeTags,forceExcludeTags,sitesToCapture, tagging); tc.runTagger(); while(!tc.isTaggingCompleted()) { try { Thread.sleep(100); }catch(InterruptedException ie) {} } tc.saveResultsToFile(validateOutputFile(fileName + ".TAGS")); tc.dumpTests(validateOutputFile(fileName + ".TESTS")); } } catch(IOException e){ System.err.println("An error has occured. This probably has to do with file input or output"); } catch(HaploViewException e){ System.err.println(e.getMessage()); } catch(PedFileException pfe) { System.err.println(pfe.getMessage()); } }
exportPLTransAction = new ExportPLTransAction();
exportPLTransAction = new ExportPLTransAction() { @Override public void actionPerformed(ActionEvent e) { try { setExportingTables(getProject().getTargetDatabase().getTables()); super.actionPerformed(e); } catch (ArchitectException ex) { ASUtils.showExceptionDialog( ArchitectFrame.this, "Error Creating List of Tables to Export", ex); } } };
private void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); prefs = PrefsUtils.getUserPrefsNode(architectSession); CoreUserSettings 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.isPlDotIniPathValid()) { 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, // blocking wait "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 == JOptionPane.CLOSED_OPTION) { throw new ArchitectException("Can't start without a pl.ini file"); } else 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); // blocking wait if (fcChoice == JFileChooser.APPROVE_OPTION) { newPlIniFile = fc.getSelectedFile(); } else { newPlIniFile = null; } } else if (choice == 1) { newPlIniFile = new File(System.getProperty("user.home"), "pl.ini"); } else throw new ArchitectException("Unexpected return from JOptionPane.showOptionDialog to get 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(); Action helpAction = new HelpAction(); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); 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)); recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { File f = new File(fileName); LoadFileWorker worker; try { worker = new LoadFileWorker(f,null); new Thread(worker).start(); } catch (FileNotFoundException e1) { JOptionPane.showMessageDialog( ArchitectFrame.this, "File not found: "+f.getPath()); } catch (Exception e1) { ASUtils.showExceptionDialog( ArchitectFrame.this, "Error loading file", e1); } } }; openProjectAction = new OpenProjectAction(recent); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( rect == null ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } if ( rect == null ) return; double zoom = Math.min(playpen.getViewportSize().getHeight()/rect.height, playpen.getViewportSize().getWidth()/rect.width); zoom *= 0.90; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.zoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Zoom to fit"); undoAction = new UndoAction(); redoAction = new RedoAction(); autoLayoutAction = new AutoLayoutAction(); autoLayout = new FruchtermanReingoldForceLayout(); autoLayoutAction.setLayout(autoLayout); exportDDLAction = new ExportDDLAction(); compareDMAction = new CompareDMAction(); exportPLTransAction = new ExportPLTransAction(); exportPLJobXMLAction = new ExportPLJobXMLAction(); quickStartAction = new QuickStartAction(); Action exportCSVAction = new AbstractAction("Export CSV File") { public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(getProject().getPlayPen().getDatabase().getTables()); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }; Action mappingReportAction = new AbstractAction("Visual Mapping Report") { // TODO convert this to an architect pane public void actionPerformed(ActionEvent e) { try { final MappingReport mr ; final List<SQLTable> selectedTables; if (playpen.getSelectedTables().size() == 0) { selectedTables = new ArrayList(playpen.getTables()); } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(ArchitectFrame.getMainInstance(),"View only the "+playpen.getSelectedTables().size()+" selected tables","Show Mapping",JOptionPane.YES_NO_OPTION)) { selectedTables = new ArrayList<SQLTable>(); for(TablePane tp: playpen.getSelectedTables()) { selectedTables.add(tp.getModel()); } } else { selectedTables = new ArrayList(playpen.getTables()); } } mr = new MappingReport(selectedTables); final JFrame f = new JFrame("Mapping Report"); // You call this a radar?? -- No sir, we call it Mr. Panel. JPanel mrPanel = new JPanel() { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); try { mr.drawHighLevelReport((Graphics2D) g,null); } catch (ArchitectException e1) { logger.error("ArchitectException while generating mapping diagram", e1); ASUtils.showExceptionDialog(ArchitectFrame.this, "Couldn't generate mapping diagram", e1); } } }; mrPanel.setDoubleBuffered(true); mrPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mrPanel.setPreferredSize(mr.getRequiredSize()); mrPanel.setOpaque(true); mrPanel.setBackground(Color.WHITE); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); JButton csv = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); csv.setText("Export CSV"); buttonBar.addGriddedGrowing(csv); ExportPLTransAction plTransaction = new ExportPLTransAction(); JButton pl = new JButton(plTransaction); plTransaction.setExportingTables(selectedTables); pl.setText("Export PL Transaction"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(pl); JButton close = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { f.setVisible(false); } }); close.setText("Close"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(close); JPanel basePane = new JPanel(new BorderLayout(5,5)); basePane.add(new JScrollPane(mrPanel),BorderLayout.CENTER); basePane.add(buttonBar.getPanel(),BorderLayout.SOUTH); f.setContentPane(basePane); f.pack(); ASUtils.centre(f); f.setVisible(true); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }; 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)); /* profiling stuff */ profileAction = new ProfilePanelAction(); //viewProfileAction = new ViewProfileAction(); not being used for second architect release menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); if (!MAC_OS_X) { fileMenu.add(prefAction); } fileMenu.add(saveSettingsAction); fileMenu.add(projectSettingsAction); if (!MAC_OS_X) { fileMenu.addSeparator(); 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); // Todo add in ability to run the engine from the architect /* Action runPL = new RunPLAction(); runPL.putValue(Action.NAME,"Run Power*Loader"); etlSubmenuOne.add(runPL); */ etlSubmenuOne.add(exportPLJobXMLAction); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); etlMenu.add(exportCSVAction); etlMenu.add(mappingReportAction); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); toolsMenu.add(new SQLRunnerAction()); menuBar.add(toolsMenu); JMenu profileMenu = new JMenu("Profile"); profileMenu.setMnemonic('p'); profileMenu.add(profileAction); //profileMenu.add(viewProfileAction);not being used for second architect release menuBar.add(profileMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); if (!MAC_OS_X) { helpMenu.add(aboutAction); helpMenu.addSeparator(); } helpMenu.add(helpAction); 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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.add(profileAction); projectBar.addSeparator(); projectBar.add(helpAction); 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.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); 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")); }
final MappingReport mr ; final List<SQLTable> selectedTables; if (playpen.getSelectedTables().size() == 0) { selectedTables = new ArrayList(playpen.getTables());
ExportCSV export = new ExportCSV(getProject().getPlayPen().getDatabase().getTables()); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile();
public void actionPerformed(ActionEvent e) { try { final MappingReport mr ; final List<SQLTable> selectedTables; if (playpen.getSelectedTables().size() == 0) { selectedTables = new ArrayList(playpen.getTables()); } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(ArchitectFrame.getMainInstance(),"View only the "+playpen.getSelectedTables().size()+" selected tables","Show Mapping",JOptionPane.YES_NO_OPTION)) { selectedTables = new ArrayList<SQLTable>(); for(TablePane tp: playpen.getSelectedTables()) { selectedTables.add(tp.getModel()); } } else { selectedTables = new ArrayList(playpen.getTables()); } } mr = new MappingReport(selectedTables); final JFrame f = new JFrame("Mapping Report"); // You call this a radar?? -- No sir, we call it Mr. Panel. JPanel mrPanel = new JPanel() { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); try { mr.drawHighLevelReport((Graphics2D) g,null); } catch (ArchitectException e1) { logger.error("ArchitectException while generating mapping diagram", e1); ASUtils.showExceptionDialog(ArchitectFrame.this, "Couldn't generate mapping diagram", e1); } } }; mrPanel.setDoubleBuffered(true); mrPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mrPanel.setPreferredSize(mr.getRequiredSize()); mrPanel.setOpaque(true); mrPanel.setBackground(Color.WHITE); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); JButton csv = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); csv.setText("Export CSV"); buttonBar.addGriddedGrowing(csv); ExportPLTransAction plTransaction = new ExportPLTransAction(); JButton pl = new JButton(plTransaction); plTransaction.setExportingTables(selectedTables); pl.setText("Export PL Transaction"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(pl); JButton close = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { f.setVisible(false); } }); close.setText("Close"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(close); JPanel basePane = new JPanel(new BorderLayout(5,5)); basePane.add(new JScrollPane(mrPanel),BorderLayout.CENTER); basePane.add(buttonBar.getPanel(),BorderLayout.SOUTH); f.setContentPane(basePane); f.pack(); ASUtils.centre(f); f.setVisible(true); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(ArchitectFrame.getMainInstance(),"View only the "+playpen.getSelectedTables().size()+" selected tables","Show Mapping",JOptionPane.YES_NO_OPTION)) { selectedTables = new ArrayList<SQLTable>(); for(TablePane tp: playpen.getSelectedTables()) { selectedTables.add(tp.getModel()); } } else { selectedTables = new ArrayList(playpen.getTables()); }
return;
public void actionPerformed(ActionEvent e) { try { final MappingReport mr ; final List<SQLTable> selectedTables; if (playpen.getSelectedTables().size() == 0) { selectedTables = new ArrayList(playpen.getTables()); } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(ArchitectFrame.getMainInstance(),"View only the "+playpen.getSelectedTables().size()+" selected tables","Show Mapping",JOptionPane.YES_NO_OPTION)) { selectedTables = new ArrayList<SQLTable>(); for(TablePane tp: playpen.getSelectedTables()) { selectedTables.add(tp.getModel()); } } else { selectedTables = new ArrayList(playpen.getTables()); } } mr = new MappingReport(selectedTables); final JFrame f = new JFrame("Mapping Report"); // You call this a radar?? -- No sir, we call it Mr. Panel. JPanel mrPanel = new JPanel() { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); try { mr.drawHighLevelReport((Graphics2D) g,null); } catch (ArchitectException e1) { logger.error("ArchitectException while generating mapping diagram", e1); ASUtils.showExceptionDialog(ArchitectFrame.this, "Couldn't generate mapping diagram", e1); } } }; mrPanel.setDoubleBuffered(true); mrPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mrPanel.setPreferredSize(mr.getRequiredSize()); mrPanel.setOpaque(true); mrPanel.setBackground(Color.WHITE); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); JButton csv = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); csv.setText("Export CSV"); buttonBar.addGriddedGrowing(csv); ExportPLTransAction plTransaction = new ExportPLTransAction(); JButton pl = new JButton(plTransaction); plTransaction.setExportingTables(selectedTables); pl.setText("Export PL Transaction"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(pl); JButton close = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { f.setVisible(false); } }); close.setText("Close"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(close); JPanel basePane = new JPanel(new BorderLayout(5,5)); basePane.add(new JScrollPane(mrPanel),BorderLayout.CENTER); basePane.add(buttonBar.getPanel(),BorderLayout.SOUTH); f.setContentPane(basePane); f.pack(); ASUtils.centre(f); f.setVisible(true); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
mr = new MappingReport(selectedTables);
public void actionPerformed(ActionEvent e) { try { final MappingReport mr ; final List<SQLTable> selectedTables; if (playpen.getSelectedTables().size() == 0) { selectedTables = new ArrayList(playpen.getTables()); } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(ArchitectFrame.getMainInstance(),"View only the "+playpen.getSelectedTables().size()+" selected tables","Show Mapping",JOptionPane.YES_NO_OPTION)) { selectedTables = new ArrayList<SQLTable>(); for(TablePane tp: playpen.getSelectedTables()) { selectedTables.add(tp.getModel()); } } else { selectedTables = new ArrayList(playpen.getTables()); } } mr = new MappingReport(selectedTables); final JFrame f = new JFrame("Mapping Report"); // You call this a radar?? -- No sir, we call it Mr. Panel. JPanel mrPanel = new JPanel() { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); try { mr.drawHighLevelReport((Graphics2D) g,null); } catch (ArchitectException e1) { logger.error("ArchitectException while generating mapping diagram", e1); ASUtils.showExceptionDialog(ArchitectFrame.this, "Couldn't generate mapping diagram", e1); } } }; mrPanel.setDoubleBuffered(true); mrPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mrPanel.setPreferredSize(mr.getRequiredSize()); mrPanel.setOpaque(true); mrPanel.setBackground(Color.WHITE); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); JButton csv = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); csv.setText("Export CSV"); buttonBar.addGriddedGrowing(csv); ExportPLTransAction plTransaction = new ExportPLTransAction(); JButton pl = new JButton(plTransaction); plTransaction.setExportingTables(selectedTables); pl.setText("Export PL Transaction"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(pl); JButton close = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { f.setVisible(false); } }); close.setText("Close"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(close); JPanel basePane = new JPanel(new BorderLayout(5,5)); basePane.add(new JScrollPane(mrPanel),BorderLayout.CENTER); basePane.add(buttonBar.getPanel(),BorderLayout.SOUTH); f.setContentPane(basePane); f.pack(); ASUtils.centre(f); f.setVisible(true); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
final JFrame f = new JFrame("Mapping Report"); JPanel mrPanel = new JPanel() { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); try { mr.drawHighLevelReport((Graphics2D) g,null); } catch (ArchitectException e1) { logger.error("ArchitectException while generating mapping diagram", e1); ASUtils.showExceptionDialog(ArchitectFrame.this, "Couldn't generate mapping diagram", e1); } } }; mrPanel.setDoubleBuffered(true); mrPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mrPanel.setPreferredSize(mr.getRequiredSize()); mrPanel.setOpaque(true); mrPanel.setBackground(Color.WHITE); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); JButton csv = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); csv.setText("Export CSV"); buttonBar.addGriddedGrowing(csv); ExportPLTransAction plTransaction = new ExportPLTransAction(); JButton pl = new JButton(plTransaction); plTransaction.setExportingTables(selectedTables); pl.setText("Export PL Transaction"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(pl); JButton close = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { f.setVisible(false); } }); close.setText("Close"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(close); JPanel basePane = new JPanel(new BorderLayout(5,5)); basePane.add(new JScrollPane(mrPanel),BorderLayout.CENTER); basePane.add(buttonBar.getPanel(),BorderLayout.SOUTH); f.setContentPane(basePane); f.pack(); ASUtils.centre(f); f.setVisible(true);
FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1);
public void actionPerformed(ActionEvent e) { try { final MappingReport mr ; final List<SQLTable> selectedTables; if (playpen.getSelectedTables().size() == 0) { selectedTables = new ArrayList(playpen.getTables()); } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(ArchitectFrame.getMainInstance(),"View only the "+playpen.getSelectedTables().size()+" selected tables","Show Mapping",JOptionPane.YES_NO_OPTION)) { selectedTables = new ArrayList<SQLTable>(); for(TablePane tp: playpen.getSelectedTables()) { selectedTables.add(tp.getModel()); } } else { selectedTables = new ArrayList(playpen.getTables()); } } mr = new MappingReport(selectedTables); final JFrame f = new JFrame("Mapping Report"); // You call this a radar?? -- No sir, we call it Mr. Panel. JPanel mrPanel = new JPanel() { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); try { mr.drawHighLevelReport((Graphics2D) g,null); } catch (ArchitectException e1) { logger.error("ArchitectException while generating mapping diagram", e1); ASUtils.showExceptionDialog(ArchitectFrame.this, "Couldn't generate mapping diagram", e1); } } }; mrPanel.setDoubleBuffered(true); mrPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); mrPanel.setPreferredSize(mr.getRequiredSize()); mrPanel.setOpaque(true); mrPanel.setBackground(Color.WHITE); ButtonBarBuilder buttonBar = new ButtonBarBuilder(); JButton csv = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } } }); csv.setText("Export CSV"); buttonBar.addGriddedGrowing(csv); ExportPLTransAction plTransaction = new ExportPLTransAction(); JButton pl = new JButton(plTransaction); plTransaction.setExportingTables(selectedTables); pl.setText("Export PL Transaction"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(pl); JButton close = new JButton(new AbstractAction(){ public void actionPerformed(ActionEvent e) { f.setVisible(false); } }); close.setText("Close"); buttonBar.addRelatedGap(); buttonBar.addGriddedGrowing(close); JPanel basePane = new JPanel(new BorderLayout(5,5)); basePane.add(new JScrollPane(mrPanel),BorderLayout.CENTER); basePane.add(buttonBar.getPanel(),BorderLayout.SOUTH); f.setContentPane(basePane); f.pack(); ASUtils.centre(f); f.setVisible(true); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
f.setVisible(false);
try { ExportCSV export = new ExportCSV(selectedTables); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); }
public void actionPerformed(ActionEvent e) { f.setVisible(false); }
ExportCSV export = new ExportCSV(getProject().getPlayPen().getDatabase().getTables()); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1);
setExportingTables(getProject().getTargetDatabase().getTables()); super.actionPerformed(e); } catch (ArchitectException ex) { ASUtils.showExceptionDialog( ArchitectFrame.this, "Error Creating List of Tables to Export", ex);
public void actionPerformed(ActionEvent e) { try { ExportCSV export = new ExportCSV(getProject().getPlayPen().getDatabase().getTables()); File file = null; JFileChooser fileDialog = new JFileChooser(); fileDialog.setSelectedFile(new File("map.csv")); if (fileDialog.showSaveDialog(ArchitectFrame.getMainInstance()) == JFileChooser.APPROVE_OPTION){ file = fileDialog.getSelectedFile(); } else { return; } FileWriter output = null; output = new FileWriter(file); output.write(export.getCSVMapping()); output.flush(); } catch (IOException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } }
try { lastSaveOpSuccessful = false; project.setSaveInProgress(true); project.save(finalSeparateThread ? pm : null); lastSaveOpSuccessful = true; JOptionPane.showMessageDialog(ArchitectFrame.this, "Save successful"); } catch (Exception ex) { lastSaveOpSuccessful = false; JOptionPane.showMessageDialog (ArchitectFrame.this, "Can't save project: "+ex.getMessage()); logger.error("Got exception while saving project", ex); } finally { project.setSaveInProgress(false); } }
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); logger.debug("current motion threshold is: " + System.getProperty("awt.dnd.drag.threshold")); System.setProperty("awt.dnd.drag.threshold","10"); logger.debug("new motion threshold is: " + System.getProperty("awt.dnd.drag.threshold")); getMainInstance().macOSXRegistration(); getMainInstance().setVisible(true); LoadFileWorker worker; if (openFile != null) { try { worker = getMainInstance().new LoadFileWorker(openFile,getMainInstance().recent); new Thread(worker).start(); } catch (FileNotFoundException e1) { JOptionPane.showMessageDialog( getMainInstance(), "File not found: "+openFile.getPath()); } catch (Exception e1) { ASUtils.showExceptionDialog( getMainInstance(), "Error loading file", e1); } } }
public void run() { try { lastSaveOpSuccessful = false; project.setSaveInProgress(true); project.save(finalSeparateThread ? pm : null); lastSaveOpSuccessful = true; JOptionPane.showMessageDialog(ArchitectFrame.this, "Save successful"); } catch (Exception ex) { lastSaveOpSuccessful = false; JOptionPane.showMessageDialog (ArchitectFrame.this, "Can't save project: "+ex.getMessage()); logger.error("Got exception while saving project", ex); } finally { project.setSaveInProgress(false); } }
displayStrings[0] = new String ("(" +((SNP)markers.elementAt(boxX)).getName() + ", " + ((SNP)markers.elementAt(boxY)).getName() + ")");
displayStrings[0] = new String ("(" +Chromosome.getMarker(boxX).getName() + ", " + Chromosome.getMarker(boxY).getName() + ")");
public void mousePressed (MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY)){ if (dPrimeTable[boxX][boxY] != null){ final SwingWorker worker = new SwingWorker(){ public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (markersLoaded){ displayStrings[0] = new String ("(" +((SNP)markers.elementAt(boxX)).getName() + ", " + ((SNP)markers.elementAt(boxY)).getName() + ")"); }else{ displayStrings[0] = new String("(" + (boxX+1) + ", " + (boxY+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int clipRightBound = (int)(clipRect.getWidth() + clipRect.getX()); int clipBotBound = (int)(clipRect.getHeight() + clipRect.getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > clipRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - clipRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > clipBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - clipBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; } }; worker.start(); } } } }
displayStrings[0] = new String("(" + (boxX+1) + ", " + (boxY+1) + ")");
displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")");
public void mousePressed (MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY)){ if (dPrimeTable[boxX][boxY] != null){ final SwingWorker worker = new SwingWorker(){ public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (markersLoaded){ displayStrings[0] = new String ("(" +((SNP)markers.elementAt(boxX)).getName() + ", " + ((SNP)markers.elementAt(boxY)).getName() + ")"); }else{ displayStrings[0] = new String("(" + (boxX+1) + ", " + (boxY+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int clipRightBound = (int)(clipRect.getWidth() + clipRect.getX()); int clipBotBound = (int)(clipRect.getHeight() + clipRect.getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > clipRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - clipRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > clipBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - clipBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; } }; worker.start(); } } } }
displayStrings[0] = new String ("(" +((SNP)markers.elementAt(boxX)).getName() + ", " + ((SNP)markers.elementAt(boxY)).getName() + ")");
displayStrings[0] = new String ("(" +Chromosome.getMarker(boxX).getName() + ", " + Chromosome.getMarker(boxY).getName() + ")");
public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (markersLoaded){ displayStrings[0] = new String ("(" +((SNP)markers.elementAt(boxX)).getName() + ", " + ((SNP)markers.elementAt(boxY)).getName() + ")"); }else{ displayStrings[0] = new String("(" + (boxX+1) + ", " + (boxY+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int clipRightBound = (int)(clipRect.getWidth() + clipRect.getX()); int clipBotBound = (int)(clipRect.getHeight() + clipRect.getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > clipRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - clipRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > clipBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - clipBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; }
displayStrings[0] = new String("(" + (boxX+1) + ", " + (boxY+1) + ")");
displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")");
public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (markersLoaded){ displayStrings[0] = new String ("(" +((SNP)markers.elementAt(boxX)).getName() + ", " + ((SNP)markers.elementAt(boxY)).getName() + ")"); }else{ displayStrings[0] = new String("(" + (boxX+1) + ", " + (boxY+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int clipRightBound = (int)(clipRect.getWidth() + clipRect.getX()); int clipBotBound = (int)(clipRect.getHeight() + clipRect.getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > clipRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - clipRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > clipBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - clipBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; }
DPrimeDisplay(PairwiseLinkage[][] t, boolean b, Vector v){
DPrimeDisplay(PairwiseLinkage[][] t, boolean b){
DPrimeDisplay(PairwiseLinkage[][] t, boolean b, Vector v){ markersLoaded = b; dPrimeTable = t; markers = v; this.setDoubleBuffered(true); addMouseListener(new PopMouseListener(this)); }
markers = v;
DPrimeDisplay(PairwiseLinkage[][] t, boolean b, Vector v){ markersLoaded = b; dPrimeTable = t; markers = v; this.setDoubleBuffered(true); addMouseListener(new PopMouseListener(this)); }
public void loadMarkers(Vector v){
public void loadMarkers(){
public void loadMarkers(Vector v){ markersLoaded = true; markers = v; repaint(); }
markers = v;
public void loadMarkers(Vector v){ markersLoaded = true; markers = v; repaint(); }
long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition();
long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.size()-1).getPosition();
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); clipRect = (Rectangle)g.getClip(); //first paint grab the cliprect for the whole viewport if (viewRect.width == 0){viewRect=clipRect;} //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. //clickxshift and clickyshift are used later to translate from x,y coords to the //pair of markers comparison at those coords if (!(markersLoaded)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); if (markersLoaded) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.25f); int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ g.setFont(markerNameFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } //System.out.println(widest); g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_NUMBER_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //// draw the marker numbers if (printDetails){ g.setFont(markerNumFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(x + 1); g.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } /** if (pref.getWidth() > viewRect.width){ //this means that the table is bigger than the display. boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } }**/ //the following values are the bounds on the boxes we want to //display given that the current window is 'clipRect lowX = (clipRect.x-clickXShift-(clipRect.y+clipRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((clipRect.x + clipRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((clipRect.x-clickXShift)+(clipRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((clipRect.x-clickXShift+clipRect.width) + (clipRect.y-clickYShift+clipRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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); g.setColor(boxColor); g.fillPolygon(diamond); if (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } }
for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos;
for (int i = 0; i < Chromosome.size(); i++) { double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos;
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); clipRect = (Rectangle)g.getClip(); //first paint grab the cliprect for the whole viewport if (viewRect.width == 0){viewRect=clipRect;} //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. //clickxshift and clickyshift are used later to translate from x,y coords to the //pair of markers comparison at those coords if (!(markersLoaded)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); if (markersLoaded) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.25f); int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ g.setFont(markerNameFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } //System.out.println(widest); g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_NUMBER_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //// draw the marker numbers if (printDetails){ g.setFont(markerNumFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(x + 1); g.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } /** if (pref.getWidth() > viewRect.width){ //this means that the table is bigger than the display. boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } }**/ //the following values are the bounds on the boxes we want to //display given that the current window is 'clipRect lowX = (clipRect.x-clickXShift-(clipRect.y+clipRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((clipRect.x + clipRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((clipRect.x-clickXShift)+(clipRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((clipRect.x-clickXShift+clipRect.width) + (clipRect.y-clickYShift+clipRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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); g.setColor(boxColor); g.fillPolygon(diamond); if (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } }
widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName());
widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName());
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); clipRect = (Rectangle)g.getClip(); //first paint grab the cliprect for the whole viewport if (viewRect.width == 0){viewRect=clipRect;} //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. //clickxshift and clickyshift are used later to translate from x,y coords to the //pair of markers comparison at those coords if (!(markersLoaded)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); if (markersLoaded) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.25f); int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ g.setFont(markerNameFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } //System.out.println(widest); g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_NUMBER_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //// draw the marker numbers if (printDetails){ g.setFont(markerNumFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(x + 1); g.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } /** if (pref.getWidth() > viewRect.width){ //this means that the table is bigger than the display. boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } }**/ //the following values are the bounds on the boxes we want to //display given that the current window is 'clipRect lowX = (clipRect.x-clickXShift-(clipRect.y+clipRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((clipRect.x + clipRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((clipRect.x-clickXShift)+(clipRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((clipRect.x-clickXShift+clipRect.width) + (clipRect.y-clickYShift+clipRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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); g.setColor(boxColor); g.fillPolygon(diamond); if (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } }
int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName());
int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName());
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); clipRect = (Rectangle)g.getClip(); //first paint grab the cliprect for the whole viewport if (viewRect.width == 0){viewRect=clipRect;} //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. //clickxshift and clickyshift are used later to translate from x,y coords to the //pair of markers comparison at those coords if (!(markersLoaded)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); if (markersLoaded) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.25f); int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ g.setFont(markerNameFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } //System.out.println(widest); g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_NUMBER_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //// draw the marker numbers if (printDetails){ g.setFont(markerNumFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(x + 1); g.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } /** if (pref.getWidth() > viewRect.width){ //this means that the table is bigger than the display. boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } }**/ //the following values are the bounds on the boxes we want to //display given that the current window is 'clipRect lowX = (clipRect.x-clickXShift-(clipRect.y+clipRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((clipRect.x + clipRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((clipRect.x-clickXShift)+(clipRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((clipRect.x-clickXShift+clipRect.width) + (clipRect.y-clickYShift+clipRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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); g.setColor(boxColor); g.fillPolygon(diamond); if (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } }
g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3);
g2.drawString(Chromosome.getMarker(x).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3);
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); clipRect = (Rectangle)g.getClip(); //first paint grab the cliprect for the whole viewport if (viewRect.width == 0){viewRect=clipRect;} //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. //clickxshift and clickyshift are used later to translate from x,y coords to the //pair of markers comparison at those coords if (!(markersLoaded)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); if (markersLoaded) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.25f); int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ g.setFont(markerNameFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } //System.out.println(widest); g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_NUMBER_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //// draw the marker numbers if (printDetails){ g.setFont(markerNumFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(x + 1); g.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } /** if (pref.getWidth() > viewRect.width){ //this means that the table is bigger than the display. boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } }**/ //the following values are the bounds on the boxes we want to //display given that the current window is 'clipRect lowX = (clipRect.x-clickXShift-(clipRect.y+clipRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((clipRect.x + clipRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((clipRect.x-clickXShift)+(clipRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((clipRect.x-clickXShift+clipRect.width) + (clipRect.y-clickYShift+clipRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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); g.setColor(boxColor); g.fillPolygon(diamond); if (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } }
String mark = String.valueOf(x + 1);
String mark = String.valueOf(Chromosome.realIndex[x] + 1);
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); clipRect = (Rectangle)g.getClip(); //first paint grab the cliprect for the whole viewport if (viewRect.width == 0){viewRect=clipRect;} //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. //clickxshift and clickyshift are used later to translate from x,y coords to the //pair of markers comparison at those coords if (!(markersLoaded)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); if (markersLoaded) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.25f); int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ g.setFont(markerNameFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } //System.out.println(widest); g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*boxSize + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_NUMBER_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //// draw the marker numbers if (printDetails){ g.setFont(markerNumFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(x + 1); g.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } /** if (pref.getWidth() > viewRect.width){ //this means that the table is bigger than the display. boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } }**/ //the following values are the bounds on the boxes we want to //display given that the current window is 'clipRect lowX = (clipRect.x-clickXShift-(clipRect.y+clipRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((clipRect.x + clipRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((clipRect.x-clickXShift)+(clipRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((clipRect.x-clickXShift+clipRect.width) + (clipRect.y-clickYShift+clipRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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); g.setColor(boxColor); g.fillPolygon(diamond); if (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } }
try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime();
filteredHaplos = theData.orderByCrossing(filteredHaplos); theData.pickTags(filteredHaplos); multidprimeArray = theData.computeMultiDprime(filteredHaplos);
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 Haplotype[][] filts; filts = new Haplotype[orderedHaplos.length][]; int numhaps = 0; 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 > Options.getHaplotypeDisplayThreshold()){ tempVector.add(orderedHaplos[i][j]); numhaps++; } } if (numhaps > 1){ printable++; numhaps=0; } filts[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filts[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 > " + Options.getHaplotypeDisplayThreshold(), "Error", JOptionPane.ERROR_MESSAGE); return; } filteredHaplos = filts; //then re-tag try{ filteredHaplos = theData.generateCrossovers(filteredHaplos); }catch (HaploViewException e){ JOptionPane.showMessageDialog(this.getParent(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } multidprimeArray = theData.getMultiDprime(); //if the haps pane exists, we want to make sure the vert scroll bar appears if necessary if (this.getParent() != null){ if (this.getPreferredSize().height > this.getParent().getHeight()){ ((JScrollPane)this.getParent().getParent()).setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); }else{ ((JScrollPane)this.getParent().getParent()).setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); } } repaint(); }
Haplotype[][] haplos = theData.generateHaplotypes(theData.blocks,false);
orderedHaplos = theData.generateHaplotypes(theData.blocks,false);
public void getHaps() throws HaploViewException{ if (theData.blocks == null) {return;} Haplotype[][] haplos = theData.generateHaplotypes(theData.blocks,false); 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(); }
orderedHaplos = new Haplotype[haplos.length][]; for (int i = 0; i < haplos.length; i++) { Vector orderedHaps = new Vector(); 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]); }
public void getHaps() throws HaploViewException{ if (theData.blocks == null) {return;} Haplotype[][] haplos = theData.generateHaplotypes(theData.blocks,false); 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(); }
} else if (parent instanceof Decorations) { Decorations item = (Decorations) parent; item.setImage(image);
public void doTag(XMLOutput output) throws JellyTagException { // invoke by body just in case some nested tag configures me invokeBody(output); Widget parent = getParentWidget(); if (parent == null) { throw new JellyTagException("This tag must be nested within a widget"); } Image image = new Image(parent.getDisplay(), getSrc()); if (parent instanceof Label) { Label label = (Label) parent; label.setImage(image); } else if (parent instanceof Button) { Button button = (Button) parent; button.setImage(image); } else if (parent instanceof Item) { Item item = (Item) parent; item.setImage(image); } else { throw new JellyTagException("This tag must be nested inside a <label>, <button> or <item> tag"); } }
public void testForObjectCompareToNull(){
public void testForObjectCompareToNull() throws ArchitectException{
public void testForObjectCompareToNull(){ SQLTable t = new SQLTable(); t.setName("Testing"); assertEquals (1, comparator.compare(t, null)); assertEquals (-1, comparator.compare(null, t)); }
public void testForObjectCompareToObject(){
public void testForObjectCompareToObject() throws ArchitectException{
public void testForObjectCompareToObject(){ SQLTable t1 = new SQLTable(); SQLTable t2 = new SQLTable(); t1.setName("cow"); t2.setName("pigs"); assertTrue( comparator.compare(t1,t2) < 0); }
public void testWithNullName() {
public void testWithNullName() throws ArchitectException {
public void testWithNullName() { SQLTable t1 = new SQLTable(); SQLTable t2 = new SQLTable(); assertEquals(0, comparator.compare(t1,t2)); }
public void testWithSameName(){
public void testWithSameName() throws ArchitectException{
public void testWithSameName(){ SQLTable t1 = new SQLTable(); SQLTable t2 = new SQLTable(); t1.setName("cow"); t2.setName("cow"); assertEquals( 0, comparator.compare(t1,t2)); }
draggingTablePanes = true;
public void mousePressed(MouseEvent evt) { requestFocus(); maybeShowPopup(evt); Point p = evt.getPoint(); unzoomPoint(p); PlayPenComponent c = contentPane.getComponentAt(p); if (c != null) p.translate(-c.getX(), -c.getY()); if (c instanceof Relationship) { if ((evt.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { // selection Relationship r = (Relationship) c; PlayPen pp = (PlayPen) r.getPlayPen(); if ( (evt.getModifiersEx() & (InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) == 0) { pp.selectNone(); } r.setSelected(true); // moving pk/fk decoration boolean overPkDec = ((RelationshipUI) r.getUI()).isOverPkDecoration(p); if (overPkDec || ((RelationshipUI) r.getUI()).isOverFkDecoration(p)) { new RelationshipDecorationMover(r, overPkDec); } } } else if (c instanceof TablePane) { evt.getComponent().requestFocus(); TablePane tp = (TablePane) c; // make sure it was a left click? if ((evt.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { // dragging try { PlayPen pp = (PlayPen) tp.getPlayPen(); int clickCol = tp.pointToColumnIndex(p); logger.debug("MP: clickCol="+clickCol+",columnsSize="+tp.getModel().getColumns().size()); if ( (evt.getModifiersEx() & (InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) == 0) { // 1. unconditionally de-select everything if this table is unselected // 2. if the table was selected, de-select everything if the click was not on the // column header of the table if (!tp.isSelected() || (clickCol > TablePane.COLUMN_INDEX_TITLE && clickCol < tp.getModel().getColumns().size()) ) { pp.selectNone(); } } // re-select the table pane (fire new selection event when appropriate) tp.setSelected(true); // de-select columns if shift and ctrl were not pressed if ( (evt.getModifiersEx() & (InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) == 0) { tp.selectNone(); } // select current column unconditionally if (clickCol < tp.getModel().getColumns().size()) { tp.selectColumn(clickCol); } // handle drag (but not if createRelationshipAction is active!) logger.debug("(mouse pressed) click col is: " + clickCol + ", column index title is: " + TablePane.COLUMN_INDEX_TITLE); logger.debug("(mouse pressed) create relationship is active: " + ArchitectFrame.getMainInstance().createRelationshipIsActive()); if (clickCol == TablePane.COLUMN_INDEX_TITLE && !ArchitectFrame.getMainInstance().createRelationshipIsActive()) { Iterator it = pp.getSelectedTables().iterator(); logger.debug("event point: " + p); logger.debug("zoomed event point: " + pp.zoomPoint(new Point(p))); while (it.hasNext()) { // create FloatingTableListener for each selected item TablePane t3 = (TablePane)it.next(); logger.debug("(" + t3.getModel().getName() + ") zoomed selected table point: " + t3.getLocationOnScreen()); logger.debug("(" + t3.getModel().getName() + ") unzoomed selected table point: " + pp.unzoomPoint(t3.getLocationOnScreen())); /* the floating table listener expects zoomed handles which are relative to the location of the table column which was clicked on. */ Point clickedColumn = tp.getLocationOnScreen(); Point otherTable = t3.getLocationOnScreen(); Point handle = pp.zoomPoint(new Point(p)); logger.debug("(" + t3.getModel().getName() + ") translation x=" + (otherTable.getX() - clickedColumn.getX()) + ",y=" + (otherTable.getY() - clickedColumn.getY())); handle.translate((int)(clickedColumn.getX() - otherTable.getX()), (int) (clickedColumn.getY() - otherTable.getY())); new PlayPen.FloatingTableListener(pp, t3, handle,false); } } } catch (ArchitectException e) { logger.error("Exception converting point to column", e); } } maybeShowPopup(evt); } else { if ((evt.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) != 0 && !evt.isPopupTrigger()) { selectNone(); rubberBandOrigin = new Point(p); rubberBand = new Rectangle(rubberBandOrigin.x, rubberBandOrigin.y, 0, 0); } } }
logger.debug("Discarding drag on titlebar (handled by mousePressed())"); draggingTablePanes = true;
throw new UnsupportedOperationException("We don't use DnD for dragging table panes");
public void dragGestureRecognized(DragGestureEvent dge) { PlayPenComponent c = contentPane.getComponentAt( unzoomPoint(((MouseEvent) dge.getTriggerEvent()).getPoint())); if ( c instanceof TablePane ) { TablePane tp = (TablePane) c; int colIndex = TablePane.COLUMN_INDEX_NONE; Point dragOrigin = tp.getPlayPen().unzoomPoint(new Point(dge.getDragOrigin())); dragOrigin.x -= tp.getX(); dragOrigin.y -= tp.getY(); // ignore drag events that aren't from the left mouse button if (dge.getTriggerEvent() instanceof MouseEvent && (dge.getTriggerEvent().getModifiers() & InputEvent.BUTTON1_MASK) == 0) return; // ignore drag events if we're in the middle of a createRelationship if (ArchitectFrame.getMainInstance().createRelationshipIsActive()) { logger.debug("CreateRelationship() is active, short circuiting DnD."); return; } try { colIndex = tp.pointToColumnIndex(dragOrigin); } catch (ArchitectException e) { logger.error("Got exception while translating drag point", e); } logger.debug("Recognized drag gesture on "+tp.getName()+"! origin="+dragOrigin +"; col="+colIndex); try { logger.debug("DGL: colIndex="+colIndex+",columnsSize="+tp.getModel().getColumns().size()); if (colIndex == TablePane.COLUMN_INDEX_TITLE) { // we don't use this because it often misses drags // that start near the edge of the titlebar logger.debug("Discarding drag on titlebar (handled by mousePressed())"); draggingTablePanes = true; } else if (colIndex >= 0 && colIndex < tp.getModel().getColumns().size()) { // export column as DnD event if (logger.isDebugEnabled()) { logger.debug("Exporting column "+colIndex+" with DnD"); } tp.draggingColumn = tp.getModel().getColumn(colIndex); DBTree tree = ArchitectFrame.getMainInstance().dbTree; int[] path = tree.getDnDPathToNode(tp.draggingColumn); if (logger.isDebugEnabled()) { StringBuffer array = new StringBuffer(); for (int i = 0; i < path.length; i++) { array.append(path[i]); array.append(","); } logger.debug("Path to dragged node: "+array); } // export list of DnD-type tree paths ArrayList paths = new ArrayList(1); paths.add(path); logger.info("DBTree: exporting 1-item list of DnD-type tree path"); JLabel label = new JLabel(tp.getModel().getName()+"."+tp.draggingColumn.getName()); Dimension labelSize = label.getPreferredSize(); label.setSize(labelSize); // because a LayoutManager would normally do this BufferedImage dragImage = new BufferedImage(labelSize.width, labelSize.height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D imageGraphics = dragImage.createGraphics(); // XXX: it would be nice to make this transparent, but initial attempts using AlphaComposite failed (on OS X) label.repaint(); imageGraphics.dispose(); dge.getDragSource().startDrag(dge, null, dragImage, new Point(0, 0), new DnDTreePathTransferable(paths), tp); } } catch (ArchitectException ex) { logger.error("Couldn't drag column", ex); JOptionPane.showMessageDialog(tp.getPlayPen(), "Can't drag column: "+ex.getMessage()); } } else { return; } }
setLayout(null);
setLayout(new PlayPenLayout());
public PlayPen() { zoom = 1.0; setBackground(java.awt.Color.white); contentPane = new PlayPenContentPane(this); setLayout(null); setName("Play Pen"); setMinimumSize(new Dimension(1,1)); dt = new DropTarget(this, new PlayPenDropListener()); bringToFrontAction = new BringToFrontAction(this); sendToBackAction = new SendToBackAction(this); setupTablePanePopup(); setupPlayPenPopup(); setupKeyboardActions(); ppMouseListener = new PPMouseListener(); addMouseListener(ppMouseListener); addMouseMotionListener(ppMouseListener); dgl = new TablePaneDragGestureListener(); ds = new DragSource(); ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, dgl); logger.debug("DragGestureRecognizer motion threshold: " + getToolkit().getDesktopProperty("DnD.gestureMotionThreshold")); }
playpen.setZoom(playpen.getZoom() + zoomStep);
playpen.setZoom(playpen.getZoom() * Math.pow(2,zoomStep));
public void actionPerformed(ActionEvent e) { logger.debug("oldZoom="+playpen.getZoom()+",zoomStep="+zoomStep); playpen.setZoom(playpen.getZoom() + zoomStep); logger.debug("newZoom="+playpen.getZoom()); Rectangle scrollTo = null; Iterator it = playpen.getSelectedItems().iterator(); while (it.hasNext()) { Rectangle bounds = ((Component) it.next()).getBounds(); logger.debug("new rectangle, bounds: " + bounds); if (scrollTo == null) { scrollTo = new Rectangle(bounds); } else { logger.debug("added rectangles, new bounds: " + scrollTo); scrollTo.add(bounds); } } if (scrollTo != null && !scrollTo.isEmpty()) { playpen.zoomRect(scrollTo); playpen.scrollRectToVisible(scrollTo); } }
if ("zoom".equals(e.getPropertyName())) { if (playpen.getZoom() + zoomStep < 0.1) { setEnabled(false); } else { setEnabled(true); } }
public void propertyChange(PropertyChangeEvent e) { if ("zoom".equals(e.getPropertyName())) { if (playpen.getZoom() + zoomStep < 0.1) { setEnabled(false); } else { setEnabled(true); } } }
return true;
MimeMultipart mimeMultipart; try { mimeMultipart = new MimeMultipart(message.getDataHandler().getDataSource()); } catch (MessagingException e) { return false; } int textPartSize = MailMatchingUtils.getMimePartSize(mimeMultipart, "text/plain"); record.setByteReceivedText(textPartSize); int binaryPartSize = MailMatchingUtils.getMimePartSize(mimeMultipart, "application/octet-stream"); record.setByteReceivedBinary(binaryPartSize); boolean textPartValid = textPartSize == record.getByteSendText(); boolean binaryPartValid = binaryPartSize == record.getByteSendBinary(); boolean valid = textPartValid && binaryPartValid; return valid;
public boolean validate(Message message, MailProcessingRecord record) { return true; }
final PhotoInfoDlg staticThis = this;
protected void createUI() { editor = new PhotoInfoEditor( ctrl ); getContentPane().add( editor, BorderLayout.NORTH ); JButton okBtn = new JButton( "OK" ); okBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } setVisible( false ); } } ); JButton applyBtn = new JButton( "Apply" ); applyBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } } } ); JButton discardBtn = new JButton( "Discard" ); discardBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); } } ); JButton closeBtn = new JButton( "Close" ); closeBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); setVisible( false ); } } ); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(okBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(applyBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(discardBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(closeBtn); getContentPane().add( buttonPane, BorderLayout.SOUTH ); getRootPane().setDefaultButton( applyBtn ); pack(); }
public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); }
public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true;
protected void createUI() { editor = new PhotoInfoEditor( ctrl ); getContentPane().add( editor, BorderLayout.NORTH ); JButton okBtn = new JButton( "OK" ); okBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } setVisible( false ); } } ); JButton applyBtn = new JButton( "Apply" ); applyBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } } } ); JButton discardBtn = new JButton( "Discard" ); discardBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); } } ); JButton closeBtn = new JButton( "Close" ); closeBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); setVisible( false ); } } ); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(okBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(applyBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(discardBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(closeBtn); getContentPane().add( buttonPane, BorderLayout.SOUTH ); getRootPane().setDefaultButton( applyBtn ); pack(); }
} } );
} catch ( Exception ex ) { JOptionPane.showMessageDialog( staticThis, "Error while saving changes: \n" + ex.getMessage(), "Error saving changes", JOptionPane.ERROR_MESSAGE, null ); log.warn( "problem while saving changes: " + ex.getMessage() ); } } } );
protected void createUI() { editor = new PhotoInfoEditor( ctrl ); getContentPane().add( editor, BorderLayout.NORTH ); JButton okBtn = new JButton( "OK" ); okBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } setVisible( false ); } } ); JButton applyBtn = new JButton( "Apply" ); applyBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } } } ); JButton discardBtn = new JButton( "Discard" ); discardBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); } } ); JButton closeBtn = new JButton( "Close" ); closeBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); setVisible( false ); } } ); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(okBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(applyBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(discardBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(closeBtn); getContentPane().add( buttonPane, BorderLayout.SOUTH ); getRootPane().setDefaultButton( applyBtn ); pack(); }
JButton applyBtn = new JButton( "Apply" ); applyBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } } } );
JButton applyBtn = new JButton( "Apply" ); applyBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { JOptionPane.showMessageDialog( staticThis, "Error while saving changes: \n" + ex.getMessage(), "Error saving changes", JOptionPane.ERROR_MESSAGE, null ); log.warn( "problem while saving changes: " + ex.getMessage() ); } } } );
protected void createUI() { editor = new PhotoInfoEditor( ctrl ); getContentPane().add( editor, BorderLayout.NORTH ); JButton okBtn = new JButton( "OK" ); okBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } setVisible( false ); } } ); JButton applyBtn = new JButton( "Apply" ); applyBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } } } ); JButton discardBtn = new JButton( "Discard" ); discardBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); } } ); JButton closeBtn = new JButton( "Close" ); closeBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { ctrl.discard(); setVisible( false ); } } ); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(okBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(applyBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(discardBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(closeBtn); getContentPane().add( buttonPane, BorderLayout.SOUTH ); getRootPane().setDefaultButton( applyBtn ); pack(); }
try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); }
try { ctrl.save(); photoChanged = true;
public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } setVisible( false ); }
}
} catch ( Exception ex ) { JOptionPane.showMessageDialog( staticThis, "Error while saving changes: \n" + ex.getMessage(), "Error saving changes", JOptionPane.ERROR_MESSAGE, null ); log.warn( "problem while saving changes: " + ex.getMessage() ); } }
public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } setVisible( false ); }
try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } }
try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { JOptionPane.showMessageDialog( staticThis, "Error while saving changes: \n" + ex.getMessage(), "Error saving changes", JOptionPane.ERROR_MESSAGE, null ); log.warn( "problem while saving changes: " + ex.getMessage() ); } }
public void actionPerformed( ActionEvent e ) { try { ctrl.save(); photoChanged = true; } catch ( Exception ex ) { log.warn( "problem while saving changes: " + ex.getMessage() ); } }
public void saveDprimeToText(String[][] dPrimeTable, String infile) throws IOException{ File dumpDprimeFile = new File(infile);
public void saveDprimeToText(String[][] dPrimeTable, File dumpDprimeFile) throws IOException{
public void saveDprimeToText(String[][] dPrimeTable, String infile) throws IOException{ File dumpDprimeFile = new File(infile); FileWriter saveDprimeWriter = new FileWriter(dumpDprimeFile); saveDprimeWriter.write("L1\tL2\tD'\tLOD\tr^2\tCIlow\tCIhi\n"); for (int i = 0; i < dPrimeTable.length; i++){ for (int j = 0; j < dPrimeTable[i].length; j++){ //many "slots" in table aren't filled in because it is a 1/2 matrix if (i < j){ saveDprimeWriter.write(i + "\t" + j + "\t" + dPrimeTable[i][j] + "\n"); } } } saveDprimeWriter.close(); }
public void saveHapsToText(Haplotype[][] finishedHaplos, String saveName) throws IOException{
public void saveHapsToText(Haplotype[][] finishedHaplos, File saveHapsFile) throws IOException{
public void saveHapsToText(Haplotype[][] finishedHaplos, String saveName) throws IOException{ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); //open file for saving haps text File saveHapsFile = new File(saveName); FileWriter saveHapsWriter = new FileWriter(saveHapsFile); int[][]lookupPos = new int[finishedHaplos.length][]; for (int p = 0; p < lookupPos.length; p++){ lookupPos[p] = new int[finishedHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][finishedHaplos[p][q].getListOrder()] = q; //System.out.println(p + " " + q + " " + finishedHaplos[p][q].getListOrder()); } } //go through each block and print haplos for (int i = 0; i < finishedHaplos.length; i++){ //write block header saveHapsWriter.write("BLOCK " + (i+1) + ". MARKERS:"); int[] markerNums = finishedHaplos[i][0].getMarkers(); for (int j = 0; j < finishedHaplos[i].length; j++){ saveHapsWriter.write(" " + (markerNums[j]+1)); } saveHapsWriter.write("\n"); //write haps and crossover percentages for (int j = 0; j < finishedHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; String theHap = new String(); int[] theGeno = finishedHaplos[i][curHapNum].getGeno(); for (int k = 0; k < theGeno.length; k++){ theHap += theGeno[k]; } saveHapsWriter.write(theHap + " (" + nf.format(finishedHaplos[i][curHapNum].getPercentage()) + ")"); if (i < finishedHaplos.length-1){ saveHapsWriter.write("\t|"); for (int crossCount = 0; crossCount < finishedHaplos[i+1].length; crossCount++){ if (crossCount != 0) saveHapsWriter.write("\t"); saveHapsWriter.write(nf.format(finishedHaplos[i][curHapNum].getCrossover(crossCount))); } saveHapsWriter.write("|"); } saveHapsWriter.write("\n"); } saveHapsWriter.write("\n"); } saveHapsWriter.close(); }
File saveHapsFile = new File(saveName);
public void saveHapsToText(Haplotype[][] finishedHaplos, String saveName) throws IOException{ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); //open file for saving haps text File saveHapsFile = new File(saveName); FileWriter saveHapsWriter = new FileWriter(saveHapsFile); int[][]lookupPos = new int[finishedHaplos.length][]; for (int p = 0; p < lookupPos.length; p++){ lookupPos[p] = new int[finishedHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][finishedHaplos[p][q].getListOrder()] = q; //System.out.println(p + " " + q + " " + finishedHaplos[p][q].getListOrder()); } } //go through each block and print haplos for (int i = 0; i < finishedHaplos.length; i++){ //write block header saveHapsWriter.write("BLOCK " + (i+1) + ". MARKERS:"); int[] markerNums = finishedHaplos[i][0].getMarkers(); for (int j = 0; j < finishedHaplos[i].length; j++){ saveHapsWriter.write(" " + (markerNums[j]+1)); } saveHapsWriter.write("\n"); //write haps and crossover percentages for (int j = 0; j < finishedHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; String theHap = new String(); int[] theGeno = finishedHaplos[i][curHapNum].getGeno(); for (int k = 0; k < theGeno.length; k++){ theHap += theGeno[k]; } saveHapsWriter.write(theHap + " (" + nf.format(finishedHaplos[i][curHapNum].getPercentage()) + ")"); if (i < finishedHaplos.length-1){ saveHapsWriter.write("\t|"); for (int crossCount = 0; crossCount < finishedHaplos[i+1].length; crossCount++){ if (crossCount != 0) saveHapsWriter.write("\t"); saveHapsWriter.write(nf.format(finishedHaplos[i][curHapNum].getCrossover(crossCount))); } saveHapsWriter.write("|"); } saveHapsWriter.write("\n"); } saveHapsWriter.write("\n"); } saveHapsWriter.close(); }
logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString(
logWriter = new LogWriter(ArchitectSessionImpl.getInstance().getUserSettings().getETLUserSettings().getString(
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; // repository connection Connection tCon = null; // target db connection try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("There is no entry for \"" + repositoryDataSource.get(ArchitectDataSource.PL_UID) + "\" in the PL_USER table"); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; String transName = null; String outputTableId = null; String inputTableId = null; for (SQLColumn outputCol : outputTable.getColumns()) { SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; outputTableNum++; } } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close repository connection", e); } try { if (tCon != null) tCon.close(); } catch (SQLException e) { logger.error("Couldn't close target connection", e); } } }
System.out.println(first + " " + last + " " + numStrong);
Vector doSFS(){ double cutHighCI = 0.98; double cutLowCI = 0.70; double recHighCI = 0.90; int numStrong = 0; int numRec = 0; int numInGroup = 0; Vector blocks = new Vector(); Vector strongPairs = new Vector(); //first make a list of marker pairs in "strong LD", sorted by distance apart for (int x = 0; x < dPrime.length-1; x++){ for (int y = x+1; y < dPrime.length; y++){ PairwiseLinkage thisPair = dPrime[x][y]; //get the right bits double lod = thisPair.getLOD(); double lowCI = thisPair.getConfidenceLow(); double highCI = thisPair.getConfidenceHigh(); if (lod < -90) continue; //missing data if (highCI < cutHighCI || lowCI < cutLowCI) continue; //must pass "strong LD" test Vector addMe = new Vector(); //a vector of x, y, separation int sep = y - x - 1; //compute separation of two markers addMe.add(String.valueOf(x)); addMe.add(String.valueOf(y)); addMe.add(String.valueOf(sep)); if (strongPairs.size() == 0){ //put first pair first strongPairs.add(addMe); }else{ //sort by descending separation of markers in each pair for (int v = 0; v < strongPairs.size(); v ++){ if (sep >= Integer.parseInt((String)((Vector)strongPairs.elementAt(v)).elementAt(2))){ strongPairs.insertElementAt(addMe, v); break; } } } } } //now take this list of pairs with "strong LD" and construct blocks boolean[] usedInBlock = new boolean[dPrime.length + 1]; for (int v = 0; v < strongPairs.size(); v++){ numStrong = 0; numRec = 0; numInGroup = 0; int first = Integer.parseInt((String)((Vector)strongPairs.elementAt(v)).elementAt(0)); int last = Integer.parseInt((String)((Vector)strongPairs.elementAt(v)).elementAt(1)); //first see if this block overlaps with another: if (usedInBlock[first] || usedInBlock[last]) continue; //test this block. requires 95% of informative markers to be "strong" for (int y = first+1; y <= last; y++){ //loop over columns in row y for (int x = first; x < y; x++){ PairwiseLinkage thisPair = dPrime[x][y]; //get the right bits double lod = thisPair.getLOD(); double lowCI = thisPair.getConfidenceLow(); double highCI = thisPair.getConfidenceHigh(); if (lod < -90) continue; //monomorphic marker error if (lod == 0 && lowCI == 0 && highCI == 0) continue; //skip bad markers if (lowCI > cutLowCI && highCI > cutHighCI) { //System.out.println(first + "\t" + last + "\t" + x + "\t" + y); numStrong++; //strong LD } if (highCI < recHighCI) numRec++; //recombination numInGroup ++; } } System.out.println(first + " " + last + " " + numStrong); //change the definition somewhat for small blocks if (numInGroup > 3){ if (numStrong + numRec < 6) continue; }else if (numInGroup > 2){ if (numStrong + numRec < 3) continue; }else{ if (numStrong + numRec < 1) continue; } if (numStrong/(numStrong + numRec) > 0.95){ //this qualifies as a block //add to the block list, but in order by first marker number: if (blocks.size() == 0){ //put first block first blocks.add(first + " " + last); }else{ //sort by ascending separation of markers in each pair boolean placed = false; for (int b = 0; b < blocks.size(); b ++){ StringTokenizer st = new StringTokenizer((String)blocks.elementAt(b)); if (first < Integer.parseInt(st.nextToken())){ blocks.insertElementAt(first + " " + last, b); placed = true; break; } } //make sure to put in blocks which fall on the tail end if (!placed) blocks.add(first + " " + last); } for (int used = first; used <= last; used++){ usedInBlock[used] = true; } } } return stringVec2intVec(blocks); }
if (numStrong/(numStrong + numRec) > 0.95){
if ((double)numStrong/(double)(numStrong + numRec) > 0.95){
Vector doSFS(){ double cutHighCI = 0.98; double cutLowCI = 0.70; double recHighCI = 0.90; int numStrong = 0; int numRec = 0; int numInGroup = 0; Vector blocks = new Vector(); Vector strongPairs = new Vector(); //first make a list of marker pairs in "strong LD", sorted by distance apart for (int x = 0; x < dPrime.length-1; x++){ for (int y = x+1; y < dPrime.length; y++){ PairwiseLinkage thisPair = dPrime[x][y]; //get the right bits double lod = thisPair.getLOD(); double lowCI = thisPair.getConfidenceLow(); double highCI = thisPair.getConfidenceHigh(); if (lod < -90) continue; //missing data if (highCI < cutHighCI || lowCI < cutLowCI) continue; //must pass "strong LD" test Vector addMe = new Vector(); //a vector of x, y, separation int sep = y - x - 1; //compute separation of two markers addMe.add(String.valueOf(x)); addMe.add(String.valueOf(y)); addMe.add(String.valueOf(sep)); if (strongPairs.size() == 0){ //put first pair first strongPairs.add(addMe); }else{ //sort by descending separation of markers in each pair for (int v = 0; v < strongPairs.size(); v ++){ if (sep >= Integer.parseInt((String)((Vector)strongPairs.elementAt(v)).elementAt(2))){ strongPairs.insertElementAt(addMe, v); break; } } } } } //now take this list of pairs with "strong LD" and construct blocks boolean[] usedInBlock = new boolean[dPrime.length + 1]; for (int v = 0; v < strongPairs.size(); v++){ numStrong = 0; numRec = 0; numInGroup = 0; int first = Integer.parseInt((String)((Vector)strongPairs.elementAt(v)).elementAt(0)); int last = Integer.parseInt((String)((Vector)strongPairs.elementAt(v)).elementAt(1)); //first see if this block overlaps with another: if (usedInBlock[first] || usedInBlock[last]) continue; //test this block. requires 95% of informative markers to be "strong" for (int y = first+1; y <= last; y++){ //loop over columns in row y for (int x = first; x < y; x++){ PairwiseLinkage thisPair = dPrime[x][y]; //get the right bits double lod = thisPair.getLOD(); double lowCI = thisPair.getConfidenceLow(); double highCI = thisPair.getConfidenceHigh(); if (lod < -90) continue; //monomorphic marker error if (lod == 0 && lowCI == 0 && highCI == 0) continue; //skip bad markers if (lowCI > cutLowCI && highCI > cutHighCI) { //System.out.println(first + "\t" + last + "\t" + x + "\t" + y); numStrong++; //strong LD } if (highCI < recHighCI) numRec++; //recombination numInGroup ++; } } System.out.println(first + " " + last + " " + numStrong); //change the definition somewhat for small blocks if (numInGroup > 3){ if (numStrong + numRec < 6) continue; }else if (numInGroup > 2){ if (numStrong + numRec < 3) continue; }else{ if (numStrong + numRec < 1) continue; } if (numStrong/(numStrong + numRec) > 0.95){ //this qualifies as a block //add to the block list, but in order by first marker number: if (blocks.size() == 0){ //put first block first blocks.add(first + " " + last); }else{ //sort by ascending separation of markers in each pair boolean placed = false; for (int b = 0; b < blocks.size(); b ++){ StringTokenizer st = new StringTokenizer((String)blocks.elementAt(b)); if (first < Integer.parseInt(st.nextToken())){ blocks.insertElementAt(first + " " + last, b); placed = true; break; } } //make sure to put in blocks which fall on the tail end if (!placed) blocks.add(first + " " + last); } for (int used = first; used <= last; used++){ usedInBlock[used] = true; } } } return stringVec2intVec(blocks); }
Script script = parser.parse(getUrl().openStream());
Script script = parser.parse(getUrl().toString());
protected Script compileScript() throws Exception { XMLParser parser = new XMLParser(); parser.setContext(getJellyContext()); Script script = parser.parse(getUrl().openStream()); script = script.compile(); if (log.isDebugEnabled()) { log.debug("Compiled script: " + getUrl()); } return script; }
caller.doTDT = this.doTDT.isSelected();
public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command==RAW_DATA){ load(PED); }else if (command == PHASED_DATA){ load(HAPS); }else if (command == BROWSE_GENO){ browse(GENO); }else if (command == BROWSE_INFO){ browse(INFO); }else if (command == HAPMAP_DATA){ //hapmap }else if (command == "OK"){ HaploView caller = (HaploView)this.getParent(); String[] returnStrings = {genoFileField.getText(), infoFileField.getText(), maxComparisonDistField.getText()}; if (fileType == HAPS){ caller.readPhasedGenotypes(returnStrings); }else if (fileType == PED){ caller.readPedGenotypes(returnStrings); } caller.doTDT = this.doTDT.isSelected(); if (caller.dPrimeDisplay != null){ caller.dPrimeDisplay.setVisible(false); } this.dispose(); }else if (command == "Cancel"){ this.dispose(); } }
}else if (command == "tdt"){ if(this.doTDT.isSelected()){ trioButton.setEnabled(true); ccButton.setEnabled(true); }else{ trioButton.setEnabled(false); ccButton.setEnabled(false); }
public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command==RAW_DATA){ load(PED); }else if (command == PHASED_DATA){ load(HAPS); }else if (command == BROWSE_GENO){ browse(GENO); }else if (command == BROWSE_INFO){ browse(INFO); }else if (command == HAPMAP_DATA){ //hapmap }else if (command == "OK"){ HaploView caller = (HaploView)this.getParent(); String[] returnStrings = {genoFileField.getText(), infoFileField.getText(), maxComparisonDistField.getText()}; if (fileType == HAPS){ caller.readPhasedGenotypes(returnStrings); }else if (fileType == PED){ caller.readPedGenotypes(returnStrings); } caller.doTDT = this.doTDT.isSelected(); if (caller.dPrimeDisplay != null){ caller.dPrimeDisplay.setVisible(false); } this.dispose(); }else if (command == "Cancel"){ this.dispose(); } }
JPanel tdtPanel = new JPanel(); tdtPanel.add(new JLabel("Run family trio TDT? ")); tdtPanel.add(doTDT); contents.add(tdtPanel);
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);
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); filePanel.add(botFilePanel); filePanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); contents.add(filePanel); JPanel prefsPanel = new JPanel(); maxComparisonDistField = new NumberTextField("500",4); prefsPanel.add(new JLabel("Ignore pairwise comparisons of markers >")); prefsPanel.add(maxComparisonDistField); prefsPanel.add(new JLabel("kb apart.")); contents.add(prefsPanel); doTDT = new JCheckBox(); doTDT.setSelected(false); if (ft == PED){ JPanel tdtPanel = new JPanel(); tdtPanel.add(new JLabel("Run family trio TDT? ")); tdtPanel.add(doTDT); contents.add(tdtPanel); } 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(); }
pageContext.getOut().println(componentDisplay);
pageContext.getOut().println("<div id=\""+getId()+"\">"+componentDisplay+"");
public int doStartTag() throws JspException{ HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); WebContext context = null; try{ context = WebContext.get(request); ApplicationConfig appConfig = context.getApplicationConfig(); // Graphs at cluster level are not supported yet assert !appConfig.isCluster(); String dashboardId = request.getParameter("dashBID"); DashboardConfig currentDashboardConfig = DashboardRepository.getInstance().get(dashboardId); assert currentDashboardConfig != null : "Error retrieving dashboard details"; DashboardComponent component = currentDashboardConfig.getComponents().get(getId()); String componentDisplay = component.draw(new DashboardContextImpl(context, currentDashboardConfig, (HttpServletRequest)pageContext.getRequest())); componentDisplay = MessageFormat.format(componentDisplay, getWidth(), getHeight(), Utils.getCookieValue(request, "JSESSIONID")); pageContext.getOut().println(componentDisplay); }catch(Throwable e){ logger.log(Level.SEVERE, "Error displaying component", e); }finally{ if(context != null) context.releaseResources(); } return SKIP_BODY; }
public TagScript createCustomTagScript(final String name, Attributes attributes) throws Exception {
public TagScript createCustomTagScript(String name, Attributes attributes) throws Exception {
public TagScript createCustomTagScript(final String name, Attributes attributes) throws Exception { // custom Ant tags if ( name.equals("fileScanner") ) { return new TagScript( new TagFactory() { public Tag createTag() throws Exception { return new FileScannerTag(new FileScanner()); } } ); } if ( name.equals("setProperty") ) { return new TagScript( new TagFactory() { public Tag createTag() throws Exception { return new SetPropertyTag(); } } ); } return null; }
public Tag createTag() throws Exception {
public Tag createTag(String name, Attributes attributes) throws Exception {
public TagScript createCustomTagScript(final String name, Attributes attributes) throws Exception { // custom Ant tags if ( name.equals("fileScanner") ) { return new TagScript( new TagFactory() { public Tag createTag() throws Exception { return new FileScannerTag(new FileScanner()); } } ); } if ( name.equals("setProperty") ) { return new TagScript( new TagFactory() { public Tag createTag() throws Exception { return new SetPropertyTag(); } } ); } return null; }
public Tag createTag() throws Exception {
public Tag createTag(String name, Attributes attributes) throws Exception {
public Tag createTag() throws Exception { return new FileScannerTag(new FileScanner()); }
public Tag createTag() throws Exception {
public Tag createTag(String name, Attributes attributes) throws Exception {
public Tag createTag() throws Exception { return new SetPropertyTag(); }
public Tag createTag(String name) throws Exception {
public Tag createTag(String name, Attributes attributes) throws Exception {
public Tag createTag(String name) throws Exception { AntTag tag = new AntTag( name ); if ( name.equals( "echo" ) ) { tag.setTrim(false); } return tag; }
public TagScript createTagScript(final String name, Attributes attributes) throws Exception {
public TagScript createTagScript(String name, Attributes attributes) throws Exception {
public TagScript createTagScript(final String name, Attributes attributes) throws Exception { TagScript answer = createCustomTagScript(name, attributes); if ( answer == null ) { answer = new TagScript( new TagFactory() { public Tag createTag() throws Exception { return AntTagLibrary.this.createTag(name); } } ); } return answer; }
public Tag createTag() throws Exception { return AntTagLibrary.this.createTag(name);
public Tag createTag(String name, Attributes attributes) throws Exception { return AntTagLibrary.this.createTag(name, attributes);
public TagScript createTagScript(final String name, Attributes attributes) throws Exception { TagScript answer = createCustomTagScript(name, attributes); if ( answer == null ) { answer = new TagScript( new TagFactory() { public Tag createTag() throws Exception { return AntTagLibrary.this.createTag(name); } } ); } return answer; }
public Tag createTag() throws Exception { return AntTagLibrary.this.createTag(name);
public Tag createTag(String name, Attributes attributes) throws Exception { return AntTagLibrary.this.createTag(name, attributes);
public Tag createTag() throws Exception { return AntTagLibrary.this.createTag(name); }
BufferedReader bufferedReader = new BufferedReader(reader); while (true) { String line = bufferedReader.readLine(); if (line == null) { break; } else { buffer.append(line); buffer.append('\n'); } } return buffer.toString();
try { BufferedReader bufferedReader = new BufferedReader(reader); while (true) { String line = bufferedReader.readLine(); if (line == null) { break; } else { buffer.append(line); buffer.append('\n'); } } return buffer.toString(); } finally { try { reader.close(); } catch (Exception e) { log.error( "Caught exception closing Reader: " + e, e); } }
protected String loadText(Reader reader) throws Exception { StringBuffer buffer = new StringBuffer(); // @todo its probably more efficient to use a fixed char[] buffer instead BufferedReader bufferedReader = new BufferedReader(reader); while (true) { String line = bufferedReader.readLine(); if (line == null) { break; } else { buffer.append(line); buffer.append('\n'); } } return buffer.toString(); }
System.out.println("Running pl");
logger.debug("Running pl");
public void actionPerformed(ActionEvent e) { File plEngine = new File(ArchitectFrame.getMainInstance().getUserSettings().getETLUserSettings().getString(ETLUserSettings.PROP_PL_ENGINE_PATH,"")); File plDir = plEngine.getParentFile(); File engineExe = new File(plDir, "PowerLoader_odbc.exe"); final StringBuffer commandLine = getPLCommandLine(); System.out.println("Running pl"); if ( engineExe.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { final Process proc = Runtime.getRuntime().exec(commandLine.toString()); // Could in theory make this use ArchitectPanelBuilder, by creating // a JPanel subclass, but may not be worthwhile as it has both an // Abort and a Close button... final JDialog pld = new JDialog(ArchitectFrame.getMainInstance(), "Power*Loader Engine"); EngineExecPanel eep = new EngineExecPanel(commandLine.toString(), proc); pld.setContentPane(eep); Action closeAction = new CommonCloseAction(pld); JButton abortButton = new JButton(eep.getAbortAction()); JDefaultButton closeButton = new JDefaultButton(closeAction); JCheckBox scrollLockCheckBox = new JCheckBox(eep.getScrollBarLockAction()); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); buttonPanel.add(abortButton); buttonPanel.add(closeButton); buttonPanel.add(scrollLockCheckBox); eep.add(buttonPanel, BorderLayout.SOUTH); pld.getRootPane().setDefaultButton(closeButton); pld.pack(); pld.setLocationRelativeTo(ArchitectFrame.getMainInstance()); pld.setVisible(true); } catch (IOException ie){ JOptionPane.showMessageDialog(ArchitectFrame.getMainInstance(), "Unexpected Exception running Engine:\n"+ie); logger.error("IOException while trying to run engine.",ie); } } }); } }
return (name.hashCode() + (int)(position ^ (position >>> 32)));
if (name != null){ return (name.hashCode() + (int)(position ^ (position >>> 32))); }else{ return (int)position; }
public int hashCode() { //uses idea from Long hashcode to hash position return (name.hashCode() + (int)(position ^ (position >>> 32))); }
while (--index > 0) {
while (--index >= 0) {
public void trimEndWhitespace() { int index = text.length(); while (--index > 0) { char ch = text.charAt(index); if (!Character.isWhitespace(ch)) { break; } } index++; if ( index < text.length() ) { this.text = text.substring(0,index); } }
db.addVolume( vol );
try { db.addVolume( vol ); } catch (PhotovaultException ex) { }
private boolean createDatabase() { // Ask for the admin password try { PVDatabase db = new PVDatabase(); db.setName( nameFld.getText() ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); settings.addDatabase( db ); String user = ""; String passwd = ""; if ( dbServerBtn.isSelected() ) { AdminLoginDlg loginDlg = new AdminLoginDlg( this, true ); if ( loginDlg.showDialog() == AdminLoginDlg.LOGIN_DLG_OK ) { user = loginDlg.getUsername(); passwd = loginDlg.getPasswd(); } db.setDbName( dbNameFld.getText() ); db.setDbHost( dbHostFld.getText() ); Volume vol = new Volume( "defaultVolume", volumeDirFld.getText() ); db.addVolume( vol ); } else { // Creating an embedded database db.setInstanceType( PVDatabase.TYPE_EMBEDDED ); db.setEmbeddedDirectory( new File( volumeDirFld.getText() ) ); } db.createDatabase( user, passwd ); settings.saveConfig(); } catch (PhotovaultException ex) { JOptionPane.showMessageDialog( this, ex.getMessage(), "Error creating database", JOptionPane.ERROR_MESSAGE ); return false; } JOptionPane.showMessageDialog( this, "Database " + nameFld.getText() + " created successfully", "Database created", JOptionPane.INFORMATION_MESSAGE ); return true; }
System.out.println( "SQL_FILE_FILTER:"+ ((FileExtensionFilter) ASUtils.SQL_FILE_FILTER).toString());
logger.info( "SQL_FILE_FILTER:"+ ((FileExtensionFilter) ASUtils.SQL_FILE_FILTER).toString());
private JPanel buildPanel() { FormLayout sqlLayout = new FormLayout( "4dlu, min:grow, 4dlu", //columns "pref, 4dlu, pref, 6dlu, fill:300dlu:grow,6dlu, pref, 6dlu, pref"); //rows CellConstraints cc = new CellConstraints(); sqlDoc = new DefaultStyledDocument(); SimpleAttributeSet att = new SimpleAttributeSet(); StyleConstants.setForeground(att, Color.black); for (DDLStatement ddl : statements){ try { sqlDoc.insertString(sqlDoc.getLength(),ddl.getSQLText(),att); } catch(BadLocationException e) { ASUtils.showExceptionDialog( "Could not create document for results", e); logger.error("Could not create document for results", e); } } sqlScriptArea = new JTextPane(); sqlScriptArea.setMargin(new Insets(6, 10, 4, 6)); sqlScriptArea.setDocument(sqlDoc); sqlScriptArea.setEditable(false); sqlScriptArea.setAutoscrolls(true); JScrollPane sp = new JScrollPane(sqlScriptArea); Action copy = new CopyAction(sqlDoc); Action execute = null; if ( targetDataSource != null ) { execute = new AbstractAction(){ public void actionPerformed(ActionEvent e) { new Thread(executeTask).start(); } }; } Action save = new AbstractAction(){ public void actionPerformed(ActionEvent e) { System.out.println( "SQL_FILE_FILTER:"+ ((FileExtensionFilter) ASUtils.SQL_FILE_FILTER).toString()); SaveDocument sd = new SaveDocument(parent,sqlDoc, (FileExtensionFilter) ASUtils.SQL_FILE_FILTER ); } }; CloseAction close = new CloseAction(); close.setWhatToClose(this); ButtonBarBuilder barBuilder = new ButtonBarBuilder(); JButton copyButton = new JButton(copy); copyButton.setText("Copy"); barBuilder.addGridded (copyButton); barBuilder.addRelatedGap(); barBuilder.addGlue(); JButton executeButton = new JButton(execute); executeButton.setText("Execute"); barBuilder.addGridded(executeButton); barBuilder.addRelatedGap(); barBuilder.addGlue(); if ( execute == null ) { executeButton.setEnabled(false); } JButton saveButton = new JButton(save); saveButton.setText("Save"); barBuilder.addGridded(saveButton); barBuilder.addRelatedGap(); barBuilder.addGlue(); JButton closeButton = new JButton(close); closeButton.setText("Close"); barBuilder.addGridded(closeButton); PanelBuilder pb; JPanel panel = logger.isDebugEnabled() ? new FormDebugPanel(sqlLayout) : new JPanel(sqlLayout); pb = new PanelBuilder(sqlLayout, panel); pb.setDefaultDialogBorder(); pb.add(new JLabel(header), cc.xy(2, 1)); if (targetDataSource != null) { pb.add(new JLabel("Your Target Database is "+ targetDataSource.getName() ), cc.xy(2, 3)); } pb.add(sp, cc.xy(2, 5)); pb.add(barBuilder.getPanel(), cc.xy(2, 7, "c,c")); pb.add(progressBar, cc.xy(2, 9)); return pb.getPanel(); }
System.out.println( "SQL_FILE_FILTER:"+ ((FileExtensionFilter) ASUtils.SQL_FILE_FILTER).toString());
logger.info( "SQL_FILE_FILTER:"+ ((FileExtensionFilter) ASUtils.SQL_FILE_FILTER).toString());
public void actionPerformed(ActionEvent e) { System.out.println( "SQL_FILE_FILTER:"+ ((FileExtensionFilter) ASUtils.SQL_FILE_FILTER).toString()); SaveDocument sd = new SaveDocument(parent,sqlDoc, (FileExtensionFilter) ASUtils.SQL_FILE_FILTER ); }
"Do not which source to compare from");
"Do not know which source to compare from");
public SQLObject getObjectToCompare() throws ArchitectException, IOException { SQLObject o; if (playPenRadio.isSelected()) { o = ArchitectFrame.getMainInstance().playpen.getDatabase(); } else if (physicalRadio.isSelected()) { if (schemaDropdown.getSelectedItem() != null) { o = (SQLObject) schemaDropdown.getSelectedItem(); } else if (catalogDropdown.getSelectedItem() != null) { o = (SQLObject) catalogDropdown.getSelectedItem(); } else if (databaseDropdown.getSelectedItem() != null) { o = getDatabase(); } else { throw new IllegalStateException( "You elected to compare a physical database, " + "but have not selected a " + "schema, catalog, or database to compare."); } } else if (loadRadio.isSelected()) { SwingUIProject project = new SwingUIProject("Source"); File f = new File(loadFilePath.getText()); project.load(new BufferedInputStream(new FileInputStream(f))); o = project.getTargetDatabase(); } else { throw new IllegalStateException( "Do not which source to compare from"); } return o; }
table.getColumnModel().getColumn(8).setPreferredWidth(100);
public PlinkResultsPanel(HaploView h, Vector results, Vector colNames, Vector filters){ hv = h; setLayout(new GridBagLayout()); plinkTableModel = new PlinkTableModel(colNames,results); sorter = new TableSorter(plinkTableModel); table = new JTable(sorter); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getTableHeader().setReorderingAllowed(false); //table.getModel().addTableModelListener(this); sorter.setTableHeader(table.getTableHeader()); table.getColumnModel().getColumn(2).setPreferredWidth(100); table.getColumnModel().getColumn(3).setPreferredWidth(100); table.getColumnModel().getColumn(8).setPreferredWidth(100); final PlinkCellRenderer renderer = new PlinkCellRenderer(); try{ table.setDefaultRenderer(Class.forName("java.lang.Double"), renderer); table.setDefaultRenderer(Class.forName("java.lang.Integer"), renderer); table.setDefaultRenderer(Class.forName("java.lang.Long"), renderer); table.setDefaultRenderer(Class.forName("java.lang.String"),renderer); }catch (Exception e){ } JScrollPane tableScroller = new JScrollPane(table); //tableScroller.setMinimumSize(new Dimension(800,600)); //tableScroller.setMaximumSize(new Dimension(800,(int)tableScroller.getPreferredSize().getHeight())); JPanel chromFilterPanel = new JPanel(); chromFilterPanel.setMinimumSize(new Dimension(700,40)); chromFilterPanel.add(new JLabel("Chromosome:")); chromChooser = new JComboBox(chromNames); chromFilterPanel.add(chromChooser); chromFilterPanel.add(new JLabel("Start kb:")); chromStart = new NumberTextField("",6,false); chromFilterPanel.add(chromStart); chromFilterPanel.add(new JLabel("End kb:")); chromEnd = new NumberTextField("",6,false); chromFilterPanel.add(chromEnd); chromFilterPanel.add(new JLabel("Other:")); genericChooser = new JComboBox(plinkTableModel.getUnknownColumns()); genericChooser.setSelectedIndex(-1); chromFilterPanel.add(genericChooser); signChooser = new JComboBox(signs); signChooser.setSelectedIndex(-1); chromFilterPanel.add(signChooser); valueField = new JTextField(8); chromFilterPanel.add(valueField); JButton doFilter = new JButton("Filter"); doFilter.addActionListener(this); chromFilterPanel.add(doFilter); JPanel topResultsFilterPanel = new JPanel(); JLabel topLabel = new JLabel("View top"); topResultsFilterPanel.add(topLabel); topField = new NumberTextField("100",6,false); topResultsFilterPanel.add(topField); JLabel resultsLabel = new JLabel("results"); topResultsFilterPanel.add(resultsLabel); JButton doTopFilter = new JButton("Go"); doTopFilter.setActionCommand("top filter"); doTopFilter.addActionListener(this); topResultsFilterPanel.add(doTopFilter); if (!plinkTableModel.pColExists()){ topLabel.setEnabled(false); topField.setEnabled(false); resultsLabel.setEnabled(false); doTopFilter.setEnabled(false); } JButton resetFilters = new JButton("Reset Filters"); resetFilters.addActionListener(this); JButton moreResults = new JButton("Load Additional Results"); moreResults.addActionListener(this); JPanel filterPanel = new JPanel(new GridBagLayout()); GridBagConstraints a = new GridBagConstraints(); filterPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Filters")); ((TitledBorder)(filterPanel.getBorder())).setTitleColor(Color.black); //a.gridx = 1; a.gridwidth = 5; a.anchor = GridBagConstraints.CENTER; a.weightx = 1; filterPanel.add(chromFilterPanel,a); a.gridy = 1; filterPanel.add(topResultsFilterPanel,a); a.gridy = 2; //a.gridx = 0; a.gridwidth = 1; a.anchor = GridBagConstraints.SOUTHWEST; filterPanel.add(moreResults,a); a.gridx = 2; a.anchor = GridBagConstraints.SOUTHEAST; filterPanel.add(resetFilters,a); JPanel goPanel = new JPanel(); JButton goButton = new JButton("<html><b>Go to Selected Region</b>"); goButton.addActionListener(this); goButton.setActionCommand("Go to Selected Region"); goPanel.add(goButton); GridBagConstraints c = new GridBagConstraints(); c.fill = 1; c.weightx = 1; c.weighty = 1; c.insets = new Insets(10,50,10,50); add(tableScroller, c); c.weighty = 0; c.gridy = 1; add(filterPanel, c); c.gridy = 2; c.weighty = 0; add(goPanel,c); if (filters != null){ if (((String)filters.get(0)).equals("")){ chromChooser.setSelectedIndex(0); }else{ chromChooser.setSelectedIndex(new Integer((String)filters.get(0)).intValue()); } if (((String)filters.get(1)).equals("") || ((String)filters.get(2)).equals("")){ chromStart.setText(""); chromEnd.setText(""); }else if (new Integer((String)filters.get(1)).intValue() > 0 && new Integer((String)filters.get(2)).intValue() > 0){ chromStart.setText((String)filters.get(1)); chromEnd.setText((String)filters.get(2)); } if (!((String)filters.get(3)).equals("0")){ genericChooser.setSelectedIndex(new Integer((String)filters.get(3)).intValue()); signChooser.setSelectedIndex(new Integer((String)filters.get(4)).intValue()); valueField.setText((String)filters.get(5)); } doFilters(); } }
this.webContext = webContext; this.dashboardConfig = dashboardConfig; this.request = request; setServerPath();
this(webContext, dashboardConfig, request, false);
public DashboardContextImpl(WebContext webContext, DashboardConfig dashboardConfig, HttpServletRequest request){ this.webContext = webContext; this.dashboardConfig = dashboardConfig; this.request = request; setServerPath(); }
typeMap.put(new Integer(Types.LONGVARCHAR), new GenericTypeDescriptor("TEXT", Types.LONGVARCHAR, 4000000000L, "'", "'", DatabaseMetaData.columnNullable, true, false));
typeMap.put(new Integer(Types.LONGVARCHAR), new GenericTypeDescriptor("TEXT", Types.LONGVARCHAR, 4000000000L, "'", "'", DatabaseMetaData.columnNullable, false, false));
protected void createTypeMap() throws SQLException { typeMap = new HashMap(); typeMap.put(new Integer(Types.BIGINT), new GenericTypeDescriptor("NUMERIC", Types.BIGINT, 1000, null, null, DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.BINARY), new GenericTypeDescriptor("BYTEA", Types.BINARY, 4000000000L, null, null, DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.BIT), new GenericTypeDescriptor("BIT", Types.BIT, 1, null, null, DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.BLOB), new GenericTypeDescriptor("BYTEA", Types.BLOB, 4000000000L, null, null, DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.CHAR), new GenericTypeDescriptor("CHAR", Types.CHAR, 4000000000L, "'", "'", DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.CLOB), new GenericTypeDescriptor("TEXT", Types.CLOB, 4000000000L, null, null, DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.DATE), new GenericTypeDescriptor("DATE", Types.DATE, 0, "'", "'", DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.DECIMAL), new GenericTypeDescriptor("NUMERIC", Types.DECIMAL, 1000, null, null, DatabaseMetaData.columnNullable, true, true)); typeMap.put(new Integer(Types.DOUBLE), new GenericTypeDescriptor("DOUBLE PRECISION", Types.DOUBLE, 38, null, null, DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.FLOAT), new GenericTypeDescriptor("REAL", Types.FLOAT, 38, null, null, DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.INTEGER), new GenericTypeDescriptor("INTEGER", Types.INTEGER, 38, null, null, DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.LONGVARBINARY), new GenericTypeDescriptor("BYTEA", Types.LONGVARBINARY, 4000000000L, null, null, DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.LONGVARCHAR), new GenericTypeDescriptor("TEXT", Types.LONGVARCHAR, 4000000000L, "'", "'", DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.NUMERIC), new GenericTypeDescriptor("NUMERIC", Types.NUMERIC, 1000, null, null, DatabaseMetaData.columnNullable, true, true)); typeMap.put(new Integer(Types.REAL), new GenericTypeDescriptor("REAL", Types.REAL, 38, null, null, DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.SMALLINT), new GenericTypeDescriptor("SMALLINT", Types.SMALLINT, 16, null, null, DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.TIME), new GenericTypeDescriptor("TIME", Types.TIME, 0, "'", "'", DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.TIMESTAMP), new GenericTypeDescriptor("TIMESTAMP", Types.TIMESTAMP, 0, "'", "'", DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.TINYINT), new GenericTypeDescriptor("SMALLINT", Types.TINYINT, 16, null, null, DatabaseMetaData.columnNullable, false, false)); typeMap.put(new Integer(Types.VARBINARY), new GenericTypeDescriptor("BYTEA", Types.VARBINARY, 4000000000L, null, null, DatabaseMetaData.columnNullable, true, false)); typeMap.put(new Integer(Types.VARCHAR), new GenericTypeDescriptor("VARCHAR", Types.VARCHAR, 4000000000L, "'", "'", DatabaseMetaData.columnNullable, true, false)); }
return name.replace(' ','_').toUpperCase();
return name.replace(' ','_').toLowerCase();
public String toIdentifier(String name) { return name.replace(' ','_').toUpperCase(); }
logger.debug("SQLTable.Folder["+getName()+"]: populate finished");
public void populate() throws ArchitectException { if (populated) return; try { if (type == COLUMNS) { parent.populateColumns(); } else if (type == IMPORTED_KEYS) { parent.populateColumns(); parent.populateRelationships(); } else if (type == EXPORTED_KEYS) { ResultSet rs = null; try { DatabaseMetaData dbmd = parent.getParentDatabase().getConnection().getMetaData(); rs = dbmd.getExportedKeys(parent.getCatalogName(), parent.getSchemaName(), parent.getName()); while (rs.next()) { if (rs.getInt(9) != 1) { // just another column mapping in a relationship we've already handled continue; } String cat = rs.getString(5); String sch = rs.getString(6); String tab = rs.getString(7); SQLTable fkTable = parent.getParentDatabase().getTableByName(cat, sch, tab); fkTable.populateColumns(); fkTable.populateRelationships(); } } catch (SQLException ex) { throw new ArchitectException("Couldn't locate related tables", ex); } finally { try { if (rs != null) rs.close(); } catch (SQLException ex) { logger.warn("Couldn't close resultset", ex); } } } else { throw new IllegalArgumentException("Unknown folder type: "+type); } } finally { populated = true; } }
logger.debug("SQLTable: populate is a no-op");
public void populate() throws ArchitectException {// populateColumns();// populateRelationships(); }
logger.debug("SQLTable: column populate finished");
private synchronized void populateColumns() throws ArchitectException { if (columnsFolder.isPopulated()) return; if (columnsFolder.children.size() > 0) throw new IllegalStateException("Can't populate table because it already contains columns"); try { SQLColumn.addColumnsToTable(this, getCatalogName(), getSchemaName(), getName()); } catch (SQLException e) { throw new ArchitectException("Failed to populate columns of table "+getName(), e); } finally { columnsFolder.populated = true; Collections.sort(columnsFolder.children, new SQLColumn.SortByPKSeq()); normalizePrimaryKey(); int newSize = columnsFolder.children.size(); int[] changedIndices = new int[newSize]; for (int i = 0; i < newSize; i++) { changedIndices[i] = i; } columnsFolder.fireDbChildrenInserted(changedIndices, columnsFolder.children); } }
logger.debug("SQLTable: relationship populate finished");
private synchronized void populateRelationships() throws ArchitectException { if (!columnsFolder.isPopulated()) throw new IllegalStateException("Table must be populated before relationships are added"); if (importedKeysFolder.isPopulated()) return; int oldSize = importedKeysFolder.children.size(); /* this must come before * SQLRelationship.addImportedRelationshipsToTable because * addImportedRelationshipsToTable causes SQLObjectEvents to be fired, * which in turn could cause infinite recursion when listeners * query the size of the relationships folder. */ importedKeysFolder.populated = true; try { SQLRelationship.addImportedRelationshipsToTable(this); } finally { int newSize = importedKeysFolder.children.size(); if (newSize > oldSize) { int[] changedIndices = new int[newSize - oldSize]; for (int i = 0, n = newSize - oldSize; i < n; i++) { changedIndices[i] = oldSize + i; } try { importedKeysFolder.fireDbChildrenInserted (changedIndices, importedKeysFolder.children.subList(oldSize, newSize)); } catch (IndexOutOfBoundsException ex) { logger.error("Index out of bounds while adding imported keys to table " +getName()+" where oldSize="+oldSize+"; newSize="+newSize +"; imported keys="+importedKeysFolder.children); } } } }
if ( db.getSchemaVersion() < PVDatabase.CURRENT_SCHEMA_VERSION ) { SchemaUpdateAction updater = new SchemaUpdateAction( db ); updater.upgradeDatabase(); }
private JUnitOJBManager() { System.setProperty( "photovault.configfile", "conf/junittest_config.xml" ); log.error( "Initializing OB for JUnit tests" ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); settings.setConfiguration( "pv_junit" ); PVDatabase db = settings.getDatabase( "pv_junit" ); if ( db == null ) { log.error( "Could not find dbname for configuration " ); return; } if ( ODMG.initODMG( "", "", db ) ) { log.debug( "Connection succesful!!!" ); } else { log.error( "Error logging into Photovault" ); } }
for (int i = 0; i < entries.length; i++) {
for (int i = 0; entries != null && i < entries.length; i++) {
private void findAllMatchingTestMail(String username) throws SamplingException { try { org.apache.commons.net.pop3.POP3Client pop3Client = openConnection(username); // retrieve all messages POP3MessageInfo[] entries = null; try { entries = pop3Client.listMessages(); } catch (Exception e) { String errorMessage = "failed to read pop3 account mail list for " + username; m_results.addError(500, errorMessage); log.info(errorMessage); return; } for (int i = 0; i < entries.length; i++) {// TODO do we need to check the state? assertEquals(1, pop3Client.getState()); POP3MessageInfo entry = entries[i]; int size = entry.size; MailProcessingRecord mailProcessingRecord = new MailProcessingRecord(); mailProcessingRecord.setReceivingQueue("pop3"); mailProcessingRecord.setTimeFetchStart(System.currentTimeMillis()); String mailText; BufferedReader mailReader = null; Reader reader = null; try { reader = pop3Client.retrieveMessage(entry.number); mailReader = new BufferedReader(reader); analyzeAndMatch(mailReader, mailProcessingRecord, pop3Client, i); } catch (Exception e) { log.info("failed to read pop3 mail #" + i + " for " + username); continue; // mail processing record is discarded } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { log.warn("error closing mail reader"); } } } continue; } closeSession(pop3Client); } catch (PostageException e) { throw new SamplingException("sample failed", e); } }
log.debug( "ImageFile = " + imageFile + " volume = " + volume.getName() + " base dir = " + volume.getBaseDir() );
public File getImageFile() { ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.READ ); txw.commit(); return imageFile; }
if(!infoFileName.equals("")) { File infoFile = new File(infoFileName); if(infoFile.exists()) { textData.prepareMarkerInput(infoFile,maxDistance,null); if(!arg_quiet){ System.out.println("Using marker file " + infoFile.getName()); } textData.infoKnown = true; } else if(!this.arg_quiet) { System.out.println("info file " + infoFileName + " does not exist"); }
File infoFile; if(infoFileName.equals("")) { infoFile = null; }else{ infoFile = new File(infoFileName);
private void processFile(String fileName,int fileType,String infoFileName){ try { int outputType; long maxDistance; long negMaxDistance; HaploData textData; File OutputFile; File inputFile; inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } maxDistance = this.arg_distance * 1000; negMaxDistance = -maxDistance; outputType = this.arg_output; textData = new HaploData(); Vector result = null; if(fileType == 0){ //read in haps file textData.prepareHapsInput(inputFile); } else if (fileType == 1) { //read in ped file /* if(this.arg_ignoreMarkers.size()>0) { for(int i=0;i<this.arg_ignoreMarkers.size();i++){ int index = Integer.parseInt((String)this.arg_ignoreMarkers.get(i)); if(index>0 && index<markerResultArray.length){ markerResultArray[index] = false; if(!this.arg_quiet) { System.out.println("Ignoring marker " + (index)); } } } }*/ result = textData.linkageToChrom(inputFile, 3, arg_skipCheck); }else{ //read in hapmapfile result = textData.linkageToChrom(inputFile,4,arg_skipCheck); } if(!infoFileName.equals("")) { File infoFile = new File(infoFileName); if(infoFile.exists()) { textData.prepareMarkerInput(infoFile,maxDistance,null); if(!arg_quiet){ System.out.println("Using marker file " + infoFile.getName()); } textData.infoKnown = true; } else if(!this.arg_quiet) { System.out.println("info file " + infoFileName + " does not exist"); } } if(this.arg_showCheck && result != null) { System.out.println("Data check results:\n" + "Name\tObsHET\tPredHET\tHWpval\t%Geno\tFamTrio\tMendErr"); for(int i=0;i<result.size();i++){ MarkerResult currentResult = (MarkerResult)result.get(i); System.out.println( Chromosome.getMarker(i).getName() +"\t"+ currentResult.getObsHet() +"\t"+ currentResult.getPredHet() +"\t"+ currentResult.getHWpvalue() +"\t"+ currentResult.getGenoPercent() +"\t"+ currentResult.getFamTrioNum() +"\t"+ currentResult.getMendErrNum()); } } if(this.arg_check && result != null){ OutputFile = new File (fileName + ".CHECK"); FileWriter saveCheckWriter = new FileWriter(OutputFile); saveCheckWriter.write("Name\tObsHET\tPredHET\tHWpval\t%Geno\tFamTrio\tMendErr\n"); for(int i=0;i<result.size();i++){ MarkerResult currentResult = (MarkerResult)result.get(i); saveCheckWriter.write( Chromosome.getMarker(i).getName() +"\t"+ currentResult.getObsHet() +"\t"+ currentResult.getPredHet() +"\t"+ currentResult.getHWpvalue() +"\t"+ currentResult.getGenoPercent() +"\t"+ currentResult.getFamTrioNum() +"\t"+ currentResult.getMendErrNum() +"\n"); } saveCheckWriter.close(); } if(outputType != -1){ textData.generateDPrimeTable(maxDistance); Haplotype[][] haplos; switch(outputType){ case BLOX_GABRIEL: OutputFile = new File(fileName + ".GABRIELblocks"); break; case BLOX_4GAM: OutputFile = new File(fileName + ".4GAMblocks"); break; case BLOX_SPINE: OutputFile = new File(fileName + ".SPINEblocks"); break; default: OutputFile = new File(fileName + ".GABRIELblocks"); break; } //this handles output type ALL int start = 0; int stop = Chromosome.getFilteredSize(); if(outputType == BLOX_ALL) { OutputFile = new File(fileName + ".GABRIELblocks"); textData.guessBlocks(BLOX_GABRIEL); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".4GAMblocks"); textData.guessBlocks(BLOX_4GAM); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".SPINEblocks"); textData.guessBlocks(BLOX_SPINE); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); }else{ textData.guessBlocks(outputType); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); } } if(this.arg_dprime) { OutputFile = new File(fileName + ".DPRIME"); if (textData.filteredDPrimeTable != null){ textData.saveDprimeToText(OutputFile, TABLE_TYPE, 0, Chromosome.getFilteredSize()); }else{ textData.saveDprimeToText(OutputFile, LIVE_TYPE, 0, Chromosome.getFilteredSize()); } } //if(fileType){ //TDT.calcTrioTDT(textData.chromosomes); //TODO: Deal with this. why do we calc TDT? and make sure not to do it except when appropriate //} } catch(IOException e){ System.err.println("An error has occured. This probably has to do with file input or output"); } catch(HaploViewException e){ System.err.println(e.getMessage()); } catch(PedFileException pfe) { System.err.println(pfe.getMessage()); } }
textData.generateDPrimeTable(maxDistance);
textData.generateDPrimeTable();
private void processFile(String fileName,int fileType,String infoFileName){ try { int outputType; long maxDistance; long negMaxDistance; HaploData textData; File OutputFile; File inputFile; inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } maxDistance = this.arg_distance * 1000; negMaxDistance = -maxDistance; outputType = this.arg_output; textData = new HaploData(); Vector result = null; if(fileType == 0){ //read in haps file textData.prepareHapsInput(inputFile); } else if (fileType == 1) { //read in ped file /* if(this.arg_ignoreMarkers.size()>0) { for(int i=0;i<this.arg_ignoreMarkers.size();i++){ int index = Integer.parseInt((String)this.arg_ignoreMarkers.get(i)); if(index>0 && index<markerResultArray.length){ markerResultArray[index] = false; if(!this.arg_quiet) { System.out.println("Ignoring marker " + (index)); } } } }*/ result = textData.linkageToChrom(inputFile, 3, arg_skipCheck); }else{ //read in hapmapfile result = textData.linkageToChrom(inputFile,4,arg_skipCheck); } if(!infoFileName.equals("")) { File infoFile = new File(infoFileName); if(infoFile.exists()) { textData.prepareMarkerInput(infoFile,maxDistance,null); if(!arg_quiet){ System.out.println("Using marker file " + infoFile.getName()); } textData.infoKnown = true; } else if(!this.arg_quiet) { System.out.println("info file " + infoFileName + " does not exist"); } } if(this.arg_showCheck && result != null) { System.out.println("Data check results:\n" + "Name\tObsHET\tPredHET\tHWpval\t%Geno\tFamTrio\tMendErr"); for(int i=0;i<result.size();i++){ MarkerResult currentResult = (MarkerResult)result.get(i); System.out.println( Chromosome.getMarker(i).getName() +"\t"+ currentResult.getObsHet() +"\t"+ currentResult.getPredHet() +"\t"+ currentResult.getHWpvalue() +"\t"+ currentResult.getGenoPercent() +"\t"+ currentResult.getFamTrioNum() +"\t"+ currentResult.getMendErrNum()); } } if(this.arg_check && result != null){ OutputFile = new File (fileName + ".CHECK"); FileWriter saveCheckWriter = new FileWriter(OutputFile); saveCheckWriter.write("Name\tObsHET\tPredHET\tHWpval\t%Geno\tFamTrio\tMendErr\n"); for(int i=0;i<result.size();i++){ MarkerResult currentResult = (MarkerResult)result.get(i); saveCheckWriter.write( Chromosome.getMarker(i).getName() +"\t"+ currentResult.getObsHet() +"\t"+ currentResult.getPredHet() +"\t"+ currentResult.getHWpvalue() +"\t"+ currentResult.getGenoPercent() +"\t"+ currentResult.getFamTrioNum() +"\t"+ currentResult.getMendErrNum() +"\n"); } saveCheckWriter.close(); } if(outputType != -1){ textData.generateDPrimeTable(maxDistance); Haplotype[][] haplos; switch(outputType){ case BLOX_GABRIEL: OutputFile = new File(fileName + ".GABRIELblocks"); break; case BLOX_4GAM: OutputFile = new File(fileName + ".4GAMblocks"); break; case BLOX_SPINE: OutputFile = new File(fileName + ".SPINEblocks"); break; default: OutputFile = new File(fileName + ".GABRIELblocks"); break; } //this handles output type ALL int start = 0; int stop = Chromosome.getFilteredSize(); if(outputType == BLOX_ALL) { OutputFile = new File(fileName + ".GABRIELblocks"); textData.guessBlocks(BLOX_GABRIEL); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".4GAMblocks"); textData.guessBlocks(BLOX_4GAM); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".SPINEblocks"); textData.guessBlocks(BLOX_SPINE); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); }else{ textData.guessBlocks(outputType); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); } } if(this.arg_dprime) { OutputFile = new File(fileName + ".DPRIME"); if (textData.filteredDPrimeTable != null){ textData.saveDprimeToText(OutputFile, TABLE_TYPE, 0, Chromosome.getFilteredSize()); }else{ textData.saveDprimeToText(OutputFile, LIVE_TYPE, 0, Chromosome.getFilteredSize()); } } //if(fileType){ //TDT.calcTrioTDT(textData.chromosomes); //TODO: Deal with this. why do we calc TDT? and make sure not to do it except when appropriate //} } catch(IOException e){ System.err.println("An error has occured. This probably has to do with file input or output"); } catch(HaploViewException e){ System.err.println(e.getMessage()); } catch(PedFileException pfe) { System.err.println(pfe.getMessage()); } }
Thumbnail thumb = photo.getThumbnail();
Thumbnail thumb = null; while ( thumb == null ) { try { thumb = photo.getThumbnail(); } catch ( Throwable e ) { log.warn( "Out of memory while creating thumbnail" ); try { sleep( 5 * 1000 ); } catch ( InterruptedException e1 ) { } } }
public void run() { synchronized ( this ) { while ( true ) { try { log.debug( "Waiting..." ); wait(); log.debug( "Waited..." ); if ( photo != null ) { log.debug( "Creating thumbnail for " + photo.getUid() ); Thumbnail thumb = photo.getThumbnail(); log.debug( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { log.debug( "drawing new thumbnail for " + lastPhoto.getUid() ); view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }