bugged
stringlengths 6
599k
| fixed
stringlengths 10
599k
| __index_level_0__
int64 0
1.13M
|
|---|---|---|
protected Project getProject() { ProjectTag tag = (ProjectTag) findAncestorWithClass(ProjectTag.class); if ( tag != null) { return tag.getProject(); } return (Project) context.findVariable( "org.apache.commons.jelly.werkz.Project" ); }
|
protected Project getProject() { ProjectTag tag = (ProjectTag) findAncestorWithClass(ProjectTag.class); if ( tag != null) { return tag.getProject(); } if (answer == null) { answer = (Project) context.findVariable( "org.apache.commons.jelly.werkz.Project" ); } return answer; }
| 1,109,576
|
public void doAssociationTests(Vector affStatus, Vector permuteInd,Vector permuteDiscPar, Vector kidAffStatus) { if(fullProbMap == null || superdata == null || realAffectedStatus == null || realKidAffectedStatus == null) { return; } if(affStatus == null){ affStatus = realAffectedStatus; } if (kidAffStatus == null){ kidAffStatus = realKidAffectedStatus; } if(permuteInd == null) { permuteInd = new Vector(); for (int i = 0; i < superdata.length; i++){ permuteInd.add(new Boolean(false)); } } if(permuteDiscPar == null) { permuteDiscPar = new Vector(); for(int i=0; i< superdata.length; i++) { permuteDiscPar.add(new Boolean(false)); } } Vector caseCounts = new Vector(); Vector controlCounts = new Vector(); if (Options.getAssocTest() == ASSOC_CC){ MapWrap totalCase = new MapWrap(0); MapWrap totalControl = new MapWrap(0); for (int i = numFilteredTrios*2; i < superdata.length; i++){ MapWrap tempCase = new MapWrap(0); MapWrap tempControl = new MapWrap(0); double tempnorm=0; for (int n=0; n<superdata[i].nsuper; n++) { Long long1 = new Long(superdata[i].superposs[n].h1); Long long2 = new Long(superdata[i].superposs[n].h2); if (((Integer)affStatus.elementAt(i)).intValue() == 1){ tempControl.put(long1,tempControl.get(long1) + superdata[i].superposs[n].p); if(!haploid[i]){ tempControl.put(long2,tempControl.get(long2) + superdata[i].superposs[n].p); } }else if (((Integer)affStatus.elementAt(i)).intValue() == 2){ tempCase.put(long1,tempCase.get(long1) + superdata[i].superposs[n].p); if(!haploid[i]){ tempCase.put(long2,tempCase.get(long2) + superdata[i].superposs[n].p); } } tempnorm += superdata[i].superposs[n].p; } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempCase.get(curHap) > 0.0000 || tempControl.get(curHap) > 0.0000) { totalCase.put(curHap,totalCase.get(curHap) + (tempCase.get(curHap)/tempnorm)); totalControl.put(curHap,totalControl.get(curHap) + (tempControl.get(curHap)/tempnorm)); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { caseCounts.add(new Double(totalCase.get(sortedKeySet.get(j)))); controlCounts.add(new Double(totalControl.get(sortedKeySet.get(j)))); } } } Vector obsT = new Vector(); Vector obsU = new Vector(); if(Options.getAssocTest() == ASSOC_TRIO) { double product; MapWrap totalT = new MapWrap(0); MapWrap totalU = new MapWrap(0); discordantCounts = new Vector(); HashMap totalDiscordantCounts = new HashMap(); for (int i=0; i<numFilteredTrios*2; i+=2) { MapWrap tempT = new MapWrap(0); MapWrap tempU = new MapWrap(0); HashMap tempDiscordantCounts = new HashMap(); double tempnorm = 0; if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ boolean discordantParentPhenos = false; if(((Integer)affStatus.elementAt(i)).intValue() != ((Integer)affStatus.elementAt(i+1)).intValue()) { discordantParentPhenos = true; } for (int n=0; n<superdata[i].nsuper; n++) { for (int m=0; m<superdata[i+1].nsuper; m++) { if(kidConsistentCache[i/2][n][m]) { product=superdata[i].superposs[n].p*superdata[i+1].superposs[m].p; Long h1 = new Long(superdata[i].superposs[n].h1); Long h2 = new Long(superdata[i].superposs[n].h2); Long h3 = new Long(superdata[i+1].superposs[m].h1); Long h4 = new Long(superdata[i+1].superposs[m].h2); if(((Boolean)permuteInd.get(i)).booleanValue()) { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempU.put(h1, tempU.get(h1) + product); tempT.put(h2, tempT.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempU.put(h3, tempU.get(h3) + product); tempT.put(h4, tempT.get(h4) + product); } } else { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempT.put(h1, tempT.get(h1) + product); tempU.put(h2, tempU.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempT.put(h3, tempT.get(h3) + product); tempU.put(h4, tempU.get(h4) + product); } } // normalize by all possibilities, even double hom tempnorm+=product; if(discordantParentPhenos) { Long aff1,aff2,unaff1,unaff2; if(((Integer)affStatus.elementAt(i)).intValue() == 2) { aff1 = h1; aff2 = h2; unaff1 = h3; unaff2 = h4; }else { unaff1 = h1; unaff2 = h2; aff1 = h3; aff2 = h4; } //if were permuting then we switch the affected and unaffected if(((Boolean)permuteDiscPar.get(i)).booleanValue()){ Long temp1 = aff1; Long temp2 = aff2; aff1 = unaff1; aff2 = unaff2; unaff1 = temp1; unaff2 = temp2; } DiscordantTally dt = getTally(aff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); if(!aff2.equals(aff1)) { dt = getTally(aff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff1.equals(aff1) && !unaff1.equals(aff2)) { dt = getTally(unaff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff2.equals(aff1) && !unaff2.equals(aff2) && !unaff2.equals(unaff1)) { dt = getTally(unaff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } } } } } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempT.get(curHap) > 0.0000 || tempU.get(curHap) > 0.0000) { totalT.put(curHap, totalT.get(curHap) + tempT.get(curHap)/tempnorm); totalU.put(curHap, totalU.get(curHap) + tempU.get(curHap)/tempnorm); } } itr = tempDiscordantCounts.keySet().iterator(); while(itr.hasNext()) { Long key = (Long)itr.next(); DiscordantTally dt = (DiscordantTally) tempDiscordantCounts.get(key); dt.normalize(tempnorm); DiscordantTally totalDT = getTally(key,totalDiscordantCounts); totalDT.combine(dt); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { obsT.add(new Double(totalT.get(sortedKeySet.get(j)))); obsU.add(new Double(totalU.get(sortedKeySet.get(j)))); if(Options.getTdtType() == TDT_PAREN) { if(totalDiscordantCounts.containsKey(sortedKeySet.get(j))) { discordantCounts.add(((DiscordantTally)totalDiscordantCounts.get(sortedKeySet.get(j))).getCounts()); }else { discordantCounts.add(new double[9]); } } } } } if (Options.getAssocTest() == ASSOC_TRIO){ this.obsT = obsT; this.obsU = obsU; } else if (Options.getAssocTest() == ASSOC_CC){ this.caseCounts = caseCounts; this.controlCounts = controlCounts; } }
|
public void doAssociationTests(Vector affStatus, Vector permuteInd,Vector permuteDiscPar, Vector kidAffStatus) { if(fullProbMap == null || superdata == null || realAffectedStatus == null || realKidAffectedStatus == null) { return; } if(affStatus == null){ affStatus = realAffectedStatus; } if (kidAffStatus == null){ kidAffStatus = realKidAffectedStatus; } if(permuteInd == null) { permuteInd = new Vector(); for (int i = 0; i < superdata.length; i++){ permuteInd.add(new Boolean(false)); } } if(permuteDiscPar == null) { permuteDiscPar = new Vector(); for(int i=0; i< superdata.length; i++) { permuteDiscPar.add(new Boolean(false)); } } Vector caseCounts = new Vector(); Vector controlCounts = new Vector(); if (Options.getAssocTest() == ASSOC_CC){ MapWrap totalCase = new MapWrap(0); MapWrap totalControl = new MapWrap(0); for (int i = numFilteredTrios*2; i < superdata.length; i++){ MapWrap tempCase = new MapWrap(0); MapWrap tempControl = new MapWrap(0); double tempnorm=0; for (int n=0; n<superdata[i].nsuper; n++) { Long long1 = new Long(superdata[i].superposs[n].h1); Long long2 = new Long(superdata[i].superposs[n].h2); if (((Integer)affStatus.elementAt(i)).intValue() == 1){ tempControl.put(long1,tempControl.get(long1) + superdata[i].superposs[n].p); if(!haploid[i]){ tempControl.put(long2,tempControl.get(long2) + superdata[i].superposs[n].p); } }else if (((Integer)affStatus.elementAt(i)).intValue() == 2){ tempCase.put(long1,tempCase.get(long1) + superdata[i].superposs[n].p); if(!haploid[i]){ tempCase.put(long2,tempCase.get(long2) + superdata[i].superposs[n].p); } } tempnorm += superdata[i].superposs[n].p; } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempCase.get(curHap) > 0.0000 || tempControl.get(curHap) > 0.0000) { totalCase.put(curHap,totalCase.get(curHap) + (tempCase.get(curHap)/tempnorm)); totalControl.put(curHap,totalControl.get(curHap) + (tempControl.get(curHap)/tempnorm)); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { caseCounts.add(new Double(totalCase.get(sortedKeySet.get(j)))); controlCounts.add(new Double(totalControl.get(sortedKeySet.get(j)))); } } } Vector obsT = new Vector(); Vector obsU = new Vector(); if(Options.getAssocTest() == ASSOC_TRIO) { double product; MapWrap totalT = new MapWrap(0); MapWrap totalU = new MapWrap(0); discordantCounts = new Vector(); HashMap totalDiscordantCounts = new HashMap(); for (int i=0; i<numFilteredTrios*2; i+=2) { MapWrap tempT = new MapWrap(0); MapWrap tempU = new MapWrap(0); HashMap tempDiscordantCounts = new HashMap(); double tempnorm = 0; if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ boolean discordantParentPhenos = false; if(Options.getTdtType() == TDT_PAREN && ((Integer)affStatus.elementAt(i)) .intValue() != ((Integer)affStatus.elementAt(i+1)).intValue()) { discordantParentPhenos = true; } for (int n=0; n<superdata[i].nsuper; n++) { for (int m=0; m<superdata[i+1].nsuper; m++) { if(kidConsistentCache[i/2][n][m]) { product=superdata[i].superposs[n].p*superdata[i+1].superposs[m].p; Long h1 = new Long(superdata[i].superposs[n].h1); Long h2 = new Long(superdata[i].superposs[n].h2); Long h3 = new Long(superdata[i+1].superposs[m].h1); Long h4 = new Long(superdata[i+1].superposs[m].h2); if(((Boolean)permuteInd.get(i)).booleanValue()) { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempU.put(h1, tempU.get(h1) + product); tempT.put(h2, tempT.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempU.put(h3, tempU.get(h3) + product); tempT.put(h4, tempT.get(h4) + product); } } else { if (superdata[i].superposs[n].h1 != superdata[i].superposs[n].h2) { tempT.put(h1, tempT.get(h1) + product); tempU.put(h2, tempU.get(h2) + product); } if (superdata[i+1].superposs[m].h1 != superdata[i+1].superposs[m].h2) { tempT.put(h3, tempT.get(h3) + product); tempU.put(h4, tempU.get(h4) + product); } } // normalize by all possibilities, even double hom tempnorm+=product; if(discordantParentPhenos) { Long aff1,aff2,unaff1,unaff2; if(((Integer)affStatus.elementAt(i)).intValue() == 2) { aff1 = h1; aff2 = h2; unaff1 = h3; unaff2 = h4; }else { unaff1 = h1; unaff2 = h2; aff1 = h3; aff2 = h4; } //if were permuting then we switch the affected and unaffected if(((Boolean)permuteDiscPar.get(i)).booleanValue()){ Long temp1 = aff1; Long temp2 = aff2; aff1 = unaff1; aff2 = unaff2; unaff1 = temp1; unaff2 = temp2; } DiscordantTally dt = getTally(aff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); if(!aff2.equals(aff1)) { dt = getTally(aff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff1.equals(aff1) && !unaff1.equals(aff2)) { dt = getTally(unaff1,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } if(!unaff2.equals(aff1) && !unaff2.equals(aff2) && !unaff2.equals(unaff1)) { dt = getTally(unaff2,tempDiscordantCounts); dt.tally(aff1.longValue(),aff2.longValue(),unaff1.longValue(),unaff2.longValue(),product); } } } } } if (tempnorm > 0.00) { Iterator itr = fullProbMap.getKeySet().iterator(); while(itr.hasNext()) { Long curHap = (Long) itr.next(); if (tempT.get(curHap) > 0.0000 || tempU.get(curHap) > 0.0000) { totalT.put(curHap, totalT.get(curHap) + tempT.get(curHap)/tempnorm); totalU.put(curHap, totalU.get(curHap) + tempU.get(curHap)/tempnorm); } } itr = tempDiscordantCounts.keySet().iterator(); while(itr.hasNext()) { Long key = (Long)itr.next(); DiscordantTally dt = (DiscordantTally) tempDiscordantCounts.get(key); dt.normalize(tempnorm); DiscordantTally totalDT = getTally(key,totalDiscordantCounts); totalDT.combine(dt); } } } } ArrayList sortedKeySet = new ArrayList(fullProbMap.getKeySet()); Collections.sort(sortedKeySet); for (int j = 0; j <sortedKeySet.size(); j++){ if (fullProbMap.get(sortedKeySet.get(j)) > .001) { obsT.add(new Double(totalT.get(sortedKeySet.get(j)))); obsU.add(new Double(totalU.get(sortedKeySet.get(j)))); if(Options.getTdtType() == TDT_PAREN) { if(totalDiscordantCounts.containsKey(sortedKeySet.get(j))) { discordantCounts.add(((DiscordantTally)totalDiscordantCounts.get(sortedKeySet.get(j))).getCounts()); }else { discordantCounts.add(new double[9]); } } } } } if (Options.getAssocTest() == ASSOC_TRIO){ this.obsT = obsT; this.obsU = obsU; } else if (Options.getAssocTest() == ASSOC_CC){ this.caseCounts = caseCounts; this.controlCounts = controlCounts; } }
| 1,109,577
|
void guessBlocks(int method){ guessBlocks(method, new Vector()); }
|
void guessBlocks(int method){ guessBlocks(method, blocks); }
| 1,109,578
|
public Vector readBlocks(File infile) throws HaploViewException, IOException{ if (!infile.exists()){ throw new HaploViewException("File " + infile.getName() + " doesn't exist!"); } Vector cust = new Vector(); BufferedReader in = new BufferedReader(new FileReader(infile)); String currentLine; int lineCount = 0; int highestYet = -1; while ((currentLine = in.readLine()) != null){ lineCount ++; StringTokenizer st = new StringTokenizer(currentLine); if (st.countTokens() == 1){ //complain if we have only one col throw new HaploViewException("File error on line " + lineCount + " in " + infile.getName()); }else if (st.countTokens() == 0){ //skip blank lines continue; } try{ Vector goodies = new Vector(); while (st.hasMoreTokens()){ Integer nextInLine = new Integer(st.nextToken()); for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input file that are "good" from checkdata //we also realign the input file to the current "good" subset since input file is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == nextInLine.intValue() - 1){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int x = 0; x < goodies.size(); x++){ thisBlock[x] = ((Integer)goodies.elementAt(x)).intValue(); if (thisBlock[x] > Chromosome.getSize() || thisBlock[x] < 0){ throw new HaploViewException("Error, marker in block out of bounds: " + thisBlock[x] + "\non line " + lineCount); } if (thisBlock[x] <= highestYet){ throw new HaploViewException("Error, markers/blocks out of order or overlap:\n" + "on line " + lineCount); } highestYet = thisBlock[x]; } cust.add(thisBlock); }catch (NumberFormatException nfe) { throw new HaploViewException("Format error on line " + lineCount + " in " + infile.getName()); } } return cust; }
|
public Vector readBlocks(File infile) throws HaploViewException, IOException{ if (!infile.exists()){ throw new HaploViewException("File " + infile.getName() + " doesn't exist!"); } Vector cust = new Vector(); BufferedReader in = new BufferedReader(new FileReader(infile)); String currentLine; int lineCount = 0; int highestYet = -1; while ((currentLine = in.readLine()) != null){ lineCount ++; StringTokenizer st = new StringTokenizer(currentLine); if (st.countTokens() == 1){ //complain if we have only one col throw new HaploViewException("File error on line " + lineCount + " in " + infile.getName()); }else if (st.countTokens() == 0){ //skip blank lines continue; } try{ Vector goodies = new Vector(); while (st.hasMoreTokens()){ Integer nextInLine = new Integer(st.nextToken()); for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input file that are "good" from checkdata //we also realign the input file to the current "good" subset since input file is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == nextInLine.intValue() - 1){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int x = 0; x < goodies.size(); x++){ thisBlock[x] = ((Integer)goodies.elementAt(x)).intValue(); if (thisBlock[x] > Chromosome.getSize() || thisBlock[x] < 0){ throw new HaploViewException("Error, marker in block out of bounds: " + thisBlock[x] + "\non line " + lineCount); } if (thisBlock[x] <= highestYet){ throw new HaploViewException("Error, markers/blocks out of order or overlap:\n" + "on line " + lineCount); } highestYet = thisBlock[x]; } if (thisBlock.length > 1){ cust.add(thisBlock); } }catch (NumberFormatException nfe) { throw new HaploViewException("Format error on line " + lineCount + " in " + infile.getName()); } } return cust; }
| 1,109,579
|
protected void computeBounds() { // XXX: should check for valid cached bounds before recomputing! TablePane pkTable = relationship.pkTable; TablePane fkTable = relationship.fkTable; if (!isOrientationLegal()) { // bestConnectionPoints also updates orientation as a side effect bestConnectionPoints(); } if (pkTable == fkTable) { // hack for supporting self-referencing table // assume orientation is PARENT_FACES_BOTTOM | CHILD_FACES_LEFT Point topLeft = new Point(fkConnectionPoint.x - getTerminationLength() * 2 - radius, fkConnectionPoint.y - getTerminationWidth()); Point bottomRight = new Point(pkConnectionPoint.x + getTerminationWidth(), pkConnectionPoint.y + radius + getTerminationLength() * 2); computedBounds = new Rectangle(topLeft.x + pkTable.getX(), topLeft.y + pkTable.getY(), bottomRight.x - topLeft.x, bottomRight.y - topLeft.y); } else { Point pkLimits = new Point(pkConnectionPoint); pkLimits.translate(pkTable.getX(), pkTable.getY()); Point fkLimits = new Point(fkConnectionPoint); fkLimits.translate(fkTable.getX(), fkTable.getY()); if (logger.isDebugEnabled()) { logger.debug("Absolute connection points: pk="+pkLimits+"; fk="+fkLimits); } // make room for parent decorations if ( (orientation & (PARENT_FACES_RIGHT | PARENT_FACES_LEFT)) != 0) { if (pkLimits.y >= fkLimits.y) { pkLimits.y += getTerminationWidth(); } else { pkLimits.y -= getTerminationWidth(); } } else { if (pkLimits.x >= fkLimits.x) { pkLimits.x += getTerminationWidth(); } else { pkLimits.x -= getTerminationWidth(); } } // make room for child decorations if ( (orientation & (CHILD_FACES_RIGHT | CHILD_FACES_LEFT)) != 0) { if (fkLimits.y <= pkConnectionPoint.y + pkTable.getY()) { fkLimits.y -= getTerminationWidth(); } else { fkLimits.y += getTerminationWidth(); } } else { if (fkLimits.x <= pkConnectionPoint.x + pkTable.getX()) { fkLimits.x -= getTerminationWidth(); } else { fkLimits.x += getTerminationWidth(); } } if (logger.isDebugEnabled()) logger.debug("Limits: pk="+pkLimits+"; fk="+fkLimits); Point topLeft = new Point(Math.min(pkLimits.x, fkLimits.x), Math.min(pkLimits.y, fkLimits.y)); Point bottomRight = new Point(Math.max(pkLimits.x, fkLimits.x), Math.max(pkLimits.y, fkLimits.y)); computedBounds = new Rectangle(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y); if (logger.isDebugEnabled()) { logger.debug("Updating bounds to "+computedBounds +" (topleft="+topLeft+"; bottomRight="+bottomRight+")"); } } relationship.setBounds(computedBounds.x, computedBounds.y, computedBounds.width, computedBounds.height); }
|
public void computeBounds() { // XXX: should check for valid cached bounds before recomputing! TablePane pkTable = relationship.pkTable; TablePane fkTable = relationship.fkTable; if (!isOrientationLegal()) { // bestConnectionPoints also updates orientation as a side effect bestConnectionPoints(); } if (pkTable == fkTable) { // hack for supporting self-referencing table // assume orientation is PARENT_FACES_BOTTOM | CHILD_FACES_LEFT Point topLeft = new Point(fkConnectionPoint.x - getTerminationLength() * 2 - radius, fkConnectionPoint.y - getTerminationWidth()); Point bottomRight = new Point(pkConnectionPoint.x + getTerminationWidth(), pkConnectionPoint.y + radius + getTerminationLength() * 2); computedBounds = new Rectangle(topLeft.x + pkTable.getX(), topLeft.y + pkTable.getY(), bottomRight.x - topLeft.x, bottomRight.y - topLeft.y); } else { Point pkLimits = new Point(pkConnectionPoint); pkLimits.translate(pkTable.getX(), pkTable.getY()); Point fkLimits = new Point(fkConnectionPoint); fkLimits.translate(fkTable.getX(), fkTable.getY()); if (logger.isDebugEnabled()) { logger.debug("Absolute connection points: pk="+pkLimits+"; fk="+fkLimits); } // make room for parent decorations if ( (orientation & (PARENT_FACES_RIGHT | PARENT_FACES_LEFT)) != 0) { if (pkLimits.y >= fkLimits.y) { pkLimits.y += getTerminationWidth(); } else { pkLimits.y -= getTerminationWidth(); } } else { if (pkLimits.x >= fkLimits.x) { pkLimits.x += getTerminationWidth(); } else { pkLimits.x -= getTerminationWidth(); } } // make room for child decorations if ( (orientation & (CHILD_FACES_RIGHT | CHILD_FACES_LEFT)) != 0) { if (fkLimits.y <= pkConnectionPoint.y + pkTable.getY()) { fkLimits.y -= getTerminationWidth(); } else { fkLimits.y += getTerminationWidth(); } } else { if (fkLimits.x <= pkConnectionPoint.x + pkTable.getX()) { fkLimits.x -= getTerminationWidth(); } else { fkLimits.x += getTerminationWidth(); } } if (logger.isDebugEnabled()) logger.debug("Limits: pk="+pkLimits+"; fk="+fkLimits); Point topLeft = new Point(Math.min(pkLimits.x, fkLimits.x), Math.min(pkLimits.y, fkLimits.y)); Point bottomRight = new Point(Math.max(pkLimits.x, fkLimits.x), Math.max(pkLimits.y, fkLimits.y)); computedBounds = new Rectangle(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y); if (logger.isDebugEnabled()) { logger.debug("Updating bounds to "+computedBounds +" (topleft="+topLeft+"; bottomRight="+bottomRight+")"); } } relationship.setBounds(computedBounds.x, computedBounds.y, computedBounds.width, computedBounds.height); }
| 1,109,580
|
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); d.setVisible(false); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, new CommonCloseAction(d)); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(tm); final JTable viewTable = new ProfileTable(tableModelSortDecorator); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths tableModelSortDecorator.initColumnSizes(viewTable); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); int response = chooser.showSaveDialog(d); if (response != JFileChooser.APPROVE_OPTION) { return; } else { File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!file.getPath().endsWith(".html")) { file = new File(file.getPath()+".html"); } } else { if (!file.getPath().endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( d, "The file\n\n"+file.getPath()+"\n\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { List tabList = new ArrayList(tables); OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file2)); if (fileFilter == ASUtils.HTML_FILE_FILTER){ final String encoding = "utf-8"; ProfileHTMLFormat prf = new ProfileHTMLFormat(encoding); OutputStreamWriter osw = new OutputStreamWriter(out, encoding); osw.append(prf.format(tabList,profileManager)); osw.flush(); } else { new ProfilePDFFormat().createPdf(out, tabList, profileManager); } } catch (Exception ex) { ASUtils.showExceptionDialog(d,"Could not save PDF File", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(d,"Could not close PDF File", ex); } } } } }; new Thread(saveTask).start(); } } }); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } ((ProfileTableModel)viewTable.getModel()).refresh(); } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete column:", e1); } } // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { profileManager.clear(); // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
|
public void actionPerformed(ActionEvent e) { if (dbTree == null) { logger.debug("dbtree was null when actionPerformed called"); return; } if ( dbTree.getSelectionPaths() == null ) { logger.debug("dbtree path selection was null when actionPerformed called"); return; } try { Set<SQLObject> sqlObject = new HashSet<SQLObject>(); for ( TreePath tp : dbTree.getSelectionPaths() ) { if ( tp.getLastPathComponent() instanceof SQLDatabase ) { sqlObject.add((SQLDatabase)tp.getLastPathComponent()); } else if ( tp.getLastPathComponent() instanceof SQLCatalog ) { SQLCatalog cat = (SQLCatalog)tp.getLastPathComponent(); sqlObject.add(cat); SQLDatabase db = ArchitectUtils.getAncestor(cat,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLSchema ) { SQLSchema sch = (SQLSchema)tp.getLastPathComponent(); sqlObject.add(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable ) { SQLTable tab = (SQLTable)tp.getLastPathComponent(); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLTable.Folder ) { SQLTable tab = ArchitectUtils.getAncestor((Folder)tp.getLastPathComponent(),SQLTable.class); sqlObject.add(tab); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } else if ( tp.getLastPathComponent() instanceof SQLColumn ) { SQLTable tab = ((SQLColumn)tp.getLastPathComponent()).getParentTable(); sqlObject.add((SQLColumn)tp.getLastPathComponent()); SQLSchema sch = ArchitectUtils.getAncestor(tab,SQLSchema.class); if ( sch != null && sqlObject.contains(sch)) sqlObject.remove(sch); SQLCatalog cat = ArchitectUtils.getAncestor(sch,SQLCatalog.class); if ( cat != null && sqlObject.contains(cat)) sqlObject.remove(cat); SQLDatabase db = ArchitectUtils.getAncestor(sch,SQLDatabase.class); if ( db != null && sqlObject.contains(db)) sqlObject.remove(db); } } final ArrayList<SQLObject> filter = new ArrayList<SQLObject>(); final Set<SQLTable> tables = new HashSet<SQLTable>(); for ( SQLObject o : sqlObject ) { if ( o instanceof SQLColumn){ tables.add(((SQLColumn)o).getParentTable()); } else { tables.addAll(ArchitectUtils.tablesUnder(o)); } if (! (o instanceof Folder)){ filter.add(o); } } profileManager.setCancelled(false); d = new JDialog(ArchitectFrame.getMainInstance(), "Table Profiles"); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent evt) { profileManager.setCancelled(true); d.setVisible(false); } }; closeAction.putValue(Action.NAME, "Close"); final JDefaultButton closeButton = new JDefaultButton(closeAction); final JPanel progressViewPanel = new JPanel(new BorderLayout()); final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(closeButton); progressViewPanel.add(buttonPanel, BorderLayout.SOUTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setPreferredSize(new Dimension(450,20)); progressViewPanel.add(progressBar, BorderLayout.CENTER); final JLabel workingOn = new JLabel("Profiling:"); progressViewPanel.add(workingOn, BorderLayout.NORTH); ArchitectPanelBuilder.makeJDialogCancellable( d, new CommonCloseAction(d)); d.getRootPane().setDefaultButton(closeButton); d.setContentPane(progressViewPanel); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); new ProgressWatcher(progressBar,profileManager,workingOn); new Thread( new Runnable() { public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(tm); final JTable viewTable = new ProfileTable(tableModelSortDecorator); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths tableModelSortDecorator.initColumnSizes(viewTable); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); int response = chooser.showSaveDialog(d); if (response != JFileChooser.APPROVE_OPTION) { return; } else { File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!file.getPath().endsWith(".html")) { file = new File(file.getPath()+".html"); } } else { if (!file.getPath().endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( d, "The file\n\n"+file.getPath()+"\n\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { List tabList = new ArrayList(tables); OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file2)); if (fileFilter == ASUtils.HTML_FILE_FILTER){ final String encoding = "utf-8"; ProfileHTMLFormat prf = new ProfileHTMLFormat(encoding); OutputStreamWriter osw = new OutputStreamWriter(out, encoding); osw.append(prf.format(tabList,profileManager)); osw.flush(); } else { new ProfilePDFFormat().createPdf(out, tabList, profileManager); } } catch (Exception ex) { ASUtils.showExceptionDialog(d,"Could not save PDF File", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(d,"Could not close PDF File", ex); } } } } }; new Thread(saveTask).start(); } } }); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete column:", e1); } } // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { profileManager.clear(); // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } } }).start(); } catch (Exception ex) { logger.error("Error in Profile Action ", ex); ASUtils.showExceptionDialog(dbTree, "Error during profile run", ex); } }
| 1,109,581
|
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(tm); final JTable viewTable = new ProfileTable(tableModelSortDecorator); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths tableModelSortDecorator.initColumnSizes(viewTable); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); int response = chooser.showSaveDialog(d); if (response != JFileChooser.APPROVE_OPTION) { return; } else { File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!file.getPath().endsWith(".html")) { file = new File(file.getPath()+".html"); } } else { if (!file.getPath().endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( d, "The file\n\n"+file.getPath()+"\n\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { List tabList = new ArrayList(tables); OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file2)); if (fileFilter == ASUtils.HTML_FILE_FILTER){ final String encoding = "utf-8"; ProfileHTMLFormat prf = new ProfileHTMLFormat(encoding); OutputStreamWriter osw = new OutputStreamWriter(out, encoding); osw.append(prf.format(tabList,profileManager)); osw.flush(); } else { new ProfilePDFFormat().createPdf(out, tabList, profileManager); } } catch (Exception ex) { ASUtils.showExceptionDialog(d,"Could not save PDF File", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(d,"Could not close PDF File", ex); } } } } }; new Thread(saveTask).start(); } } }); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } ((ProfileTableModel)viewTable.getModel()).refresh(); } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete column:", e1); } } // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { profileManager.clear(); // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
|
public void run() { try { List<SQLTable> toBeProfiled = new ArrayList<SQLTable>(); for (SQLTable t: tables) { if (profileManager.getResult(t)== null) { toBeProfiled.add(t); workingOn.setText("Adding "+t.getName()+ " ("+toBeProfiled.size()+")"); } } profileManager.createProfiles(toBeProfiled, workingOn); progressBar.setVisible(false); JLabel status = new JLabel("Generating reports, Please wait......"); progressViewPanel.add(status, BorderLayout.NORTH); status.setVisible(true); JTabbedPane tabPane = new JTabbedPane(); ProfileTableModel tm = new ProfileTableModel(); for (SQLObject sqo: filter){ tm.addFilter(sqo); } tm.setProfileManager(profileManager); TableModelSortDecorator tableModelSortDecorator = new TableModelSortDecorator(tm); final JTable viewTable = new ProfileTable(tableModelSortDecorator); JTableHeader tableHeader = viewTable.getTableHeader(); tableModelSortDecorator.setTableHeader(tableHeader); viewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); ProfilePanelMouseListener profilePanelMouseListener = new ProfilePanelMouseListener(); profilePanelMouseListener.setTabPane(tabPane); viewTable.addMouseListener( profilePanelMouseListener); JScrollPane editorScrollPane = new JScrollPane(viewTable); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); editorScrollPane.setPreferredSize(new Dimension(800, 600)); editorScrollPane.setMinimumSize(new Dimension(10, 10)); // reset column widths tableModelSortDecorator.initColumnSizes(viewTable); JPanel tableViewPane = new JPanel(new BorderLayout()); tableViewPane.add(editorScrollPane,BorderLayout.CENTER); ButtonBarBuilder buttonBuilder = new ButtonBarBuilder(); JButton save = new JButton(new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); int response = chooser.showSaveDialog(d); if (response != JFileChooser.APPROVE_OPTION) { return; } else { File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!file.getPath().endsWith(".html")) { file = new File(file.getPath()+".html"); } } else { if (!file.getPath().endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( d, "The file\n\n"+file.getPath()+"\n\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { List tabList = new ArrayList(tables); OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file2)); if (fileFilter == ASUtils.HTML_FILE_FILTER){ final String encoding = "utf-8"; ProfileHTMLFormat prf = new ProfileHTMLFormat(encoding); OutputStreamWriter osw = new OutputStreamWriter(out, encoding); osw.append(prf.format(tabList,profileManager)); osw.flush(); } else { new ProfilePDFFormat().createPdf(out, tabList, profileManager); } } catch (Exception ex) { ASUtils.showExceptionDialog(d,"Could not save PDF File", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(d,"Could not close PDF File", ex); } } } } }; new Thread(saveTask).start(); } } }); JButton refresh = new JButton(new AbstractAction("Refresh"){ public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton delete = new JButton(new AbstractAction("Delete"){ public void actionPerformed(ActionEvent e) { int[] killMe = viewTable.getSelectedRows(); Arrays.sort(killMe); // iterate backwards so the rows don't shift away on us! for (int i = killMe.length-1; i >= 0; i--) { logger.debug("Deleting row "+killMe[i]+": "+viewTable.getValueAt(killMe[i],4)); SQLColumn col = (SQLColumn) viewTable.getValueAt(killMe[i], 4); try { profileManager.remove(col); } catch (ArchitectException e1) { ASUtils.showExceptionDialog(d,"Could delete column:", e1); } } // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton deleteAll = new JButton(new AbstractAction("Delete All"){ public void actionPerformed(ActionEvent e) { profileManager.clear(); // This's ugly, depends on knowledge of wrap class order TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); } }); JButton[] buttonArray = {refresh,delete,deleteAll,save,closeButton}; buttonBuilder.addGriddedButtons(buttonArray); tableViewPane.add(buttonBuilder.getPanel(),BorderLayout.SOUTH); tabPane.addTab("Table View", tableViewPane ); ProfilePanel p = new ProfilePanel(profileManager); tabPane.addTab("Graph View",p); profilePanelMouseListener.setProfilePanel(p); List<SQLTable> list = new ArrayList(tables); p.setTables(list); p.setChartType(ChartTypes.PIE); d.setVisible(false); d.remove(progressViewPanel); d.setContentPane(tabPane); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } catch (SQLException e) { logger.error("Error in Profile Action ", e); ASUtils.showExceptionDialogNoReport(dbTree, "Error during profile run", e); } catch (ArchitectException e) { logger.error("Error in Profile Action", e); ASUtils.showExceptionDialog(dbTree, "Error during profile run", e); } }
| 1,109,582
|
public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } ((ProfileTableModel)viewTable.getModel()).refresh(); }
|
public void actionPerformed(ActionEvent e) { Set<SQLTable> uniqueTables = new HashSet(); for (int i: viewTable.getSelectedRows()) { Object o = viewTable.getValueAt(i,3); System.out.println(o.getClass()); SQLTable table = (SQLTable) o ; uniqueTables.add(table); } try { profileManager.setCancelled(false); profileManager.createProfiles(uniqueTables); } catch (SQLException e1) { throw new RuntimeException(e1); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); } TableModelSortDecorator t = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel t2 = (ProfileTableModel) t.getTableModel(); t2.refresh(); }
| 1,109,583
|
public ColumnEditPanel(SQLTable table, int idx) throws ArchitectException { super(new BorderLayout(12,12)); JPanel westPanel = new JPanel(new BorderLayout()); columns = new JList(); columns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); columns.addListSelectionListener(this); westPanel.add(new JScrollPane(columns), BorderLayout.CENTER); setModel(table); JPanel addDelPanel = new JPanel(new FlowLayout()); addDelPanel.add(addColumnButton = new JButton("Add")); addColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { try { idx = model.getColumns().size(); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); idx = 0; } } else { idx++; // add after selected column } SQLColumn col = new SQLColumn(); col.setColumnName("new column"); model.addColumn(idx, col); columns.setSelectedIndex(idx); } }); addDelPanel.add(deleteColumnButton = new JButton("Del")); deleteColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } }); westPanel.add(addDelPanel, BorderLayout.SOUTH); add(westPanel, BorderLayout.WEST); JPanel centerBox = new JPanel(); centerBox.setLayout(new BoxLayout(centerBox, BoxLayout.Y_AXIS)); centerBox.add(Box.createVerticalGlue()); JPanel centerPanel = new JPanel(); centerPanel.setLayout(new FormLayout(5, 5)); centerPanel.setBorder(BorderFactory.createTitledBorder("Column Properties")); centerPanel.add(new JLabel("Source Database")); centerPanel.add(sourceDB = new JLabel()); centerPanel.add(new JLabel("Source Table.Column")); centerPanel.add(sourceTableCol = new JLabel()); centerPanel.add(new JLabel("Name")); centerPanel.add(colName = new JTextField()); colName.addActionListener(this); colName.getDocument().addDocumentListener(this); centerPanel.add(new JLabel("Type")); centerPanel.add(colType = createColTypeEditor()); colType.addActionListener(this); centerPanel.add(new JLabel("Scale")); centerPanel.add(colScale = createScaleEditor()); colScale.addChangeListener(this); centerPanel.add(new JLabel("Precision")); centerPanel.add(colPrec = createPrecisionEditor()); colPrec.addChangeListener(this); centerPanel.add(new JLabel("In Primary Key")); centerPanel.add(colInPK = new JCheckBox()); colInPK.addActionListener(this); centerPanel.add(new JLabel("Allows Nulls")); centerPanel.add(colNullable = new JCheckBox()); colNullable.addActionListener(this); centerPanel.add(new JLabel("Auto Increment")); centerPanel.add(colAutoInc = new JCheckBox()); colAutoInc.addActionListener(this); centerPanel.add(new JLabel("Remarks")); centerPanel.add(colRemarks = new JTextField()); colRemarks.addActionListener(this); centerPanel.add(new JLabel("Default Value")); centerPanel.add(colDefaultValue = new JTextField()); colDefaultValue.addActionListener(this); Dimension maxSize = centerPanel.getLayout().preferredLayoutSize(centerPanel); maxSize.width = Integer.MAX_VALUE; centerPanel.setMaximumSize(maxSize); centerBox.add(centerPanel); centerBox.add(Box.createVerticalGlue()); add(centerBox, BorderLayout.CENTER); // select the default column columns.setSelectedIndex(idx); }
|
public ColumnEditPanel(SQLTable table, int idx) throws ArchitectException { super(new BorderLayout(12,12)); JPanel westPanel = new JPanel(new BorderLayout()); columns = new JList(); columns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); columns.addListSelectionListener(this); westPanel.add(new JScrollPane(columns), BorderLayout.CENTER); setModel(table); JPanel addDelPanel = new JPanel(new FlowLayout()); addDelPanel.add(addColumnButton = new JButton("Add")); addColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { try { idx = model.getColumns().size(); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); idx = 0; } } else { idx++; // add after selected column } SQLColumn col = new SQLColumn(); col.setColumnName("new column"); model.addColumn(idx, col); columns.setSelectedIndex(idx); } }); addDelPanel.add(deleteColumnButton = new JButton("Del")); deleteColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } }); westPanel.add(addDelPanel, BorderLayout.SOUTH); add(westPanel, BorderLayout.WEST); JPanel centerBox = new JPanel(); centerBox.setLayout(new BoxLayout(centerBox, BoxLayout.Y_AXIS)); centerBox.add(Box.createVerticalGlue()); JPanel centerPanel = new JPanel(); centerPanel.setLayout(new FormLayout(5, 5)); centerPanel.setBorder(BorderFactory.createTitledBorder("Column Properties")); centerPanel.add(new JLabel("Source Database")); centerPanel.add(sourceDB = new JLabel()); centerPanel.add(new JLabel("Source Table.Column")); centerPanel.add(sourceTableCol = new JLabel()); centerPanel.add(new JLabel("Name")); centerPanel.add(colName = new JTextField()); colName.addActionListener(this); colName.getDocument().addDocumentListener(this); centerPanel.add(new JLabel("Type")); centerPanel.add(colType = createColTypeEditor()); colType.addActionListener(this); centerPanel.add(new JLabel("Scale")); centerPanel.add(colScale = createScaleEditor()); colScale.addChangeListener(this); centerPanel.add(new JLabel("Precision")); centerPanel.add(colPrec = createPrecisionEditor()); colPrec.addChangeListener(this); centerPanel.add(new JLabel("In Primary Key")); centerPanel.add(colInPK = new JCheckBox()); colInPK.addActionListener(this); centerPanel.add(new JLabel("Allows Nulls")); centerPanel.add(colNullable = new JCheckBox()); colNullable.addActionListener(this); centerPanel.add(new JLabel("Auto Increment")); centerPanel.add(colAutoInc = new JCheckBox()); colAutoInc.addActionListener(this); centerPanel.add(new JLabel("Remarks")); centerPanel.add(colRemarks = new JTextField()); colRemarks.addActionListener(this); centerPanel.add(new JLabel("Default Value")); centerPanel.add(colDefaultValue = new JTextField()); colDefaultValue.addActionListener(this); Dimension maxSize = centerPanel.getLayout().preferredLayoutSize(centerPanel); maxSize.width = Integer.MAX_VALUE; centerPanel.setMaximumSize(maxSize); centerBox.add(centerPanel); centerBox.add(Box.createVerticalGlue()); add(centerBox, BorderLayout.CENTER); // select the default column columns.setSelectedIndex(idx); }
| 1,109,584
|
public ColumnEditPanel(SQLTable table, int idx) throws ArchitectException { super(new BorderLayout(12,12)); JPanel westPanel = new JPanel(new BorderLayout()); columns = new JList(); columns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); columns.addListSelectionListener(this); westPanel.add(new JScrollPane(columns), BorderLayout.CENTER); setModel(table); JPanel addDelPanel = new JPanel(new FlowLayout()); addDelPanel.add(addColumnButton = new JButton("Add")); addColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { try { idx = model.getColumns().size(); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); idx = 0; } } else { idx++; // add after selected column } SQLColumn col = new SQLColumn(); col.setColumnName("new column"); model.addColumn(idx, col); columns.setSelectedIndex(idx); } }); addDelPanel.add(deleteColumnButton = new JButton("Del")); deleteColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } }); westPanel.add(addDelPanel, BorderLayout.SOUTH); add(westPanel, BorderLayout.WEST); JPanel centerBox = new JPanel(); centerBox.setLayout(new BoxLayout(centerBox, BoxLayout.Y_AXIS)); centerBox.add(Box.createVerticalGlue()); JPanel centerPanel = new JPanel(); centerPanel.setLayout(new FormLayout(5, 5)); centerPanel.setBorder(BorderFactory.createTitledBorder("Column Properties")); centerPanel.add(new JLabel("Source Database")); centerPanel.add(sourceDB = new JLabel()); centerPanel.add(new JLabel("Source Table.Column")); centerPanel.add(sourceTableCol = new JLabel()); centerPanel.add(new JLabel("Name")); centerPanel.add(colName = new JTextField()); colName.addActionListener(this); colName.getDocument().addDocumentListener(this); centerPanel.add(new JLabel("Type")); centerPanel.add(colType = createColTypeEditor()); colType.addActionListener(this); centerPanel.add(new JLabel("Scale")); centerPanel.add(colScale = createScaleEditor()); colScale.addChangeListener(this); centerPanel.add(new JLabel("Precision")); centerPanel.add(colPrec = createPrecisionEditor()); colPrec.addChangeListener(this); centerPanel.add(new JLabel("In Primary Key")); centerPanel.add(colInPK = new JCheckBox()); colInPK.addActionListener(this); centerPanel.add(new JLabel("Allows Nulls")); centerPanel.add(colNullable = new JCheckBox()); colNullable.addActionListener(this); centerPanel.add(new JLabel("Auto Increment")); centerPanel.add(colAutoInc = new JCheckBox()); colAutoInc.addActionListener(this); centerPanel.add(new JLabel("Remarks")); centerPanel.add(colRemarks = new JTextField()); colRemarks.addActionListener(this); centerPanel.add(new JLabel("Default Value")); centerPanel.add(colDefaultValue = new JTextField()); colDefaultValue.addActionListener(this); Dimension maxSize = centerPanel.getLayout().preferredLayoutSize(centerPanel); maxSize.width = Integer.MAX_VALUE; centerPanel.setMaximumSize(maxSize); centerBox.add(centerPanel); centerBox.add(Box.createVerticalGlue()); add(centerBox, BorderLayout.CENTER); // select the default column columns.setSelectedIndex(idx); }
|
public ColumnEditPanel(SQLTable table, int idx) throws ArchitectException { super(new BorderLayout(12,12)); JPanel westPanel = new JPanel(new BorderLayout()); columns = new JList(); columns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); columns.addListSelectionListener(this); westPanel.add(new JScrollPane(columns), BorderLayout.CENTER); setModel(table); JPanel addDelPanel = new JPanel(new FlowLayout()); addDelPanel.add(addColumnButton = new JButton("Add")); addColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { try { idx = model.getColumns().size(); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); idx = 0; } } else { idx++; // add after selected column } SQLColumn col = new SQLColumn(); col.setColumnName("new column"); model.addColumn(idx, col); columns.setSelectedIndex(idx); } }); addDelPanel.add(deleteColumnButton = new JButton("Del")); deleteColumnButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } } }); westPanel.add(addDelPanel, BorderLayout.SOUTH); add(westPanel, BorderLayout.WEST); JPanel centerBox = new JPanel(); centerBox.setLayout(new BoxLayout(centerBox, BoxLayout.Y_AXIS)); centerBox.add(Box.createVerticalGlue()); JPanel centerPanel = new JPanel(); centerPanel.setLayout(new FormLayout(5, 5)); centerPanel.setBorder(BorderFactory.createTitledBorder("Column Properties")); centerPanel.add(new JLabel("Source Database")); centerPanel.add(sourceDB = new JLabel()); centerPanel.add(new JLabel("Source Table.Column")); centerPanel.add(sourceTableCol = new JLabel()); centerPanel.add(new JLabel("Name")); centerPanel.add(colName = new JTextField()); colName.addActionListener(this); colName.getDocument().addDocumentListener(this); centerPanel.add(new JLabel("Type")); centerPanel.add(colType = createColTypeEditor()); colType.addActionListener(this); centerPanel.add(new JLabel("Scale")); centerPanel.add(colScale = createScaleEditor()); colScale.addChangeListener(this); centerPanel.add(new JLabel("Precision")); centerPanel.add(colPrec = createPrecisionEditor()); colPrec.addChangeListener(this); centerPanel.add(new JLabel("In Primary Key")); centerPanel.add(colInPK = new JCheckBox()); colInPK.addActionListener(this); centerPanel.add(new JLabel("Allows Nulls")); centerPanel.add(colNullable = new JCheckBox()); colNullable.addActionListener(this); centerPanel.add(new JLabel("Auto Increment")); centerPanel.add(colAutoInc = new JCheckBox()); colAutoInc.addActionListener(this); centerPanel.add(new JLabel("Remarks")); centerPanel.add(colRemarks = new JTextField()); colRemarks.addActionListener(this); centerPanel.add(new JLabel("Default Value")); centerPanel.add(colDefaultValue = new JTextField()); colDefaultValue.addActionListener(this); Dimension maxSize = centerPanel.getLayout().preferredLayoutSize(centerPanel); maxSize.width = Integer.MAX_VALUE; centerPanel.setMaximumSize(maxSize); centerBox.add(centerPanel); centerBox.add(Box.createVerticalGlue()); add(centerBox, BorderLayout.CENTER); // select the default column columns.setSelectedIndex(idx); }
| 1,109,585
|
public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } }
|
public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } }
| 1,109,586
|
public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } }
|
public void actionPerformed(ActionEvent e) { int idx = columns.getSelectedIndex(); if (idx < 0) { JOptionPane.showMessageDialog(ColumnEditPanel.this, "Please select a column, then click delete"); } else { try { model.removeColumn(idx); int size = model.getColumns().size(); if (size > 0) { columns.setSelectedIndex(Math.min(idx, size-1)); } } catch (LockedColumnException ex) { JOptionPane.showMessageDialog (ColumnEditPanel.this, ex.getMessage()); } catch (ArchitectException ex) { logger.error("Couldn't count number of columns", ex); JOptionPane.showMessageDialog (ColumnEditPanel.this, "Couldn't count number of columns: "+ex.getMessage()); } } }
| 1,109,587
|
public void runScript(String uri, XMLOutput output) throws Exception { URL url = getResource(uri); if (url == null) { throw new JellyException("Could not find Jelly script: " + url); } Script script = compileScript(url); URL newJellyContextURL = getJellyContextURL(url); JellyContext newJellyContext = new JellyContext(this, newJellyContextURL); script.run(newJellyContext, output); }
|
public void runScript(String uri, XMLOutput output) throws Exception { URL url = getResource(uri); if (url == null) { throw new JellyException("Could not find Jelly script: " + url); } Script script = compileScript(url); URL newJellyContextURL = getJellyContextURL(url); JellyContext newJellyContext = new JellyContext(this, newJellyContextURL); script.run(newJellyContext, output); }
| 1,109,588
|
private final void setDatabase(SQLDatabase newdb) { if (newdb == null) throw new NullPointerException("db must be non-null"); this.db = newdb; db.setIgnoreReset(true); if (db.getDataSource() == null) { ArchitectDataSource dbcs = new ArchitectDataSource(); dbcs.setName("Not Configured"); dbcs.setDisplayName("Not Configured"); db.setDataSource(dbcs); } try { ArchitectUtils.listenToHierarchy(this, db); } catch (ArchitectException ex) { logger.error("Couldn't listen to database", ex); } tableNames = new HashSet(); }
|
private final void setDatabase(SQLDatabase newdb) { if (newdb == null) throw new NullPointerException("db must be non-null"); this.db = newdb; db.setPlayPenDatabase(true); if (db.getDataSource() == null) { ArchitectDataSource dbcs = new ArchitectDataSource(); dbcs.setName("Not Configured"); dbcs.setDisplayName("Not Configured"); db.setDataSource(dbcs); } try { ArchitectUtils.listenToHierarchy(this, db); } catch (ArchitectException ex) { logger.error("Couldn't listen to database", ex); } tableNames = new HashSet(); }
| 1,109,589
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet rs = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
| 1,109,590
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
| 1,109,591
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = rs.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
| 1,109,592
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = rs.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
| 1,109,593
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
| 1,109,594
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (mdTables != null) mdTables.close(); } } }
|
protected static void addTablesToDatabase(SQLDatabase addTo) throws SQLException, ArchitectException { HashMap catalogs = new HashMap(); HashMap schemas = new HashMap(); synchronized (addTo) { Connection con = addTo.getConnection(); DatabaseMetaData dbmd = con.getMetaData(); ResultSet mdTables = null; try { mdTables = dbmd.getTables(null, null, "%", new String[] {"TABLE", "VIEW"}); while (mdTables.next()) { SQLObject tableParent = addTo; String catName = mdTables.getString(1); SQLCatalog cat = null; if (catName != null) { cat = (SQLCatalog) catalogs.get(catName); if (cat == null) { cat = new SQLCatalog(addTo, catName); cat.setNativeTerm(dbmd.getCatalogTerm()); logger.debug("Set catalog term to "+cat.getNativeTerm()); addTo.children.add(cat); catalogs.put(catName, cat); } tableParent = cat; } String schName = mdTables.getString(2); SQLSchema schema = null; if (schName != null) { schema = (SQLSchema) schemas.get(catName+"."+schName); if (schema == null) { if (cat == null) { schema = new SQLSchema(addTo, schName, false); addTo.children.add(schema); } else { schema = new SQLSchema(cat, schName, false); cat.children.add(schema); } schema.setNativeTerm(dbmd.getSchemaTerm()); logger.debug("Set schema term to "+schema.getNativeTerm()); schemas.put(catName+"."+schName, schema); } tableParent = schema; } tableParent.children.add(new SQLTable(tableParent, mdTables.getString(3), mdTables.getString(5), mdTables.getString(4), false)); } } finally { if (rs != null) rs.close(); } } }
| 1,109,595
|
public void dbChildrenRemoved(SQLObjectEvent e) { if (e.getSource() == this.model.getColumnsFolder()) { int ci[] = e.getChangedIndices(); for (int i = 0; i < ci.length; i++) { columnSelection.remove(ci[i]); } if (columnSelection.size() > 0) { selectNone(); columnSelection.set(Math.min(ci[0], columnSelection.size()-1), Boolean.TRUE); } } try { ArchitectUtils.unlistenToHierarchy(this, e.getChildren()); if (columnSelection.size() != this.model.getColumns().size()) { logger.error("Selection list and children are out of sync: selection="+columnSelection+"; children="+model.getChildren()); } } catch (ArchitectException ex) { logger.error("Couldn't remove children", ex); JOptionPane.showMessageDialog(this, "Couldn't delete column: "+ex.getMessage()); } firePropertyChange("model.children", null, null); revalidate(); }
|
public void dbChildrenRemoved(SQLObjectEvent e) { if (e.getSource() == this.model.getColumnsFolder()) { int ci[] = e.getChangedIndices(); for (int i = 0; i < ci.length; i++) { columnSelection.remove(ci[i]); } if (columnSelection.size() > 0) { selectNone(); columnSelection.set(Math.min(ci[0], columnSelection.size()-1), Boolean.TRUE); } } try { ArchitectUtils.unlistenToHierarchy(this, e.getChildren()); if (columnSelection.size() != this.model.getColumns().size()) { logger.error("Selection list and children are out of sync: selection="+columnSelection+"; children="+this.model.getColumns()); } } catch (ArchitectException ex) { logger.error("Couldn't remove children", ex); JOptionPane.showMessageDialog(this, "Couldn't delete column: "+ex.getMessage()); } firePropertyChange("model.children", null, null); revalidate(); }
| 1,109,596
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus replica entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
| 1,109,598
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } try { replicaEntry.tryDelete(); } catch (PersistException e) { log.error("Unable to delete replica entry: " + replicaEntry, e); if (masterEntry != null) { S newReplicaEntry = mReplicaStorage.prepare(); transferToReplicaEntry(replicaEntry, masterEntry, newReplicaEntry); log.info("Replacing corrupt replica entry with: " + newReplicaEntry); try { newReplicaEntry.update(); } catch (PersistException e2) { log.error("Unable to update replica entry: " + replicaEntry, e2); return; } } } } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
| 1,109,599
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { S newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
| 1,109,600
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing replica entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
| 1,109,601
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
|
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException { if (replicaEntry == null && masterEntry == null) { return; } Log log = LogFactory.getLog(ReplicatedRepository.class); setReplicationDisabled(true); try { Transaction txn = mRepository.enterTransaction(); try { if (replicaEntry != null) { if (masterEntry == null) { log.info("Deleting bogus entry: " + replicaEntry); } replicaEntry.tryDelete(); } if (masterEntry != null) { Storable newReplicaEntry = mReplicaStorage.prepare(); if (replicaEntry == null) { masterEntry.copyAllProperties(newReplicaEntry); log.info("Adding missing entry: " + newReplicaEntry); } else { if (replicaEntry.equalProperties(masterEntry)) { return; } // First copy from old replica to preserve values of // any independent properties. Be sure not to copy // nulls from old replica to new replica, in case new // non-nullable properties have been added. This is why // copyUnequalProperties is called instead of // copyAllProperties. replicaEntry.copyUnequalProperties(newReplicaEntry); // Calling copyAllProperties will skip unsupported // independent properties in master, thus preserving // old independent property values. masterEntry.copyAllProperties(newReplicaEntry); log.info("Replacing stale entry with: " + newReplicaEntry); } if (!newReplicaEntry.tryInsert()) { // Try to correct bizarre corruption. newReplicaEntry.tryDelete(); newReplicaEntry.tryInsert(); } } txn.commit(); } finally { txn.exit(); } } finally { setReplicationDisabled(false); } }
| 1,109,602
|
public <S extends Storable> Storage<S> storageFor(Class<S> type) throws MalformedTypeException, SupportException, RepositoryException { Storage storage = mStorageMap.get(type); if (storage != null) { return storage; } Object lock; boolean doCreate; synchronized (mStorableTypeLockMap) { lock = mStorableTypeLockMap.get(type); if (lock != null) { doCreate = false; } else { doCreate = true; lock = new Object(); mStorableTypeLockMap.put(type, lock); } } synchronized (lock) { // Check storage map again before creating new storage. while (true) { storage = mStorageMap.get(type); if (storage != null) { return storage; } if (doCreate) { break; } try { lock.wait(); } catch (InterruptedException e) { throw new RepositoryException("Interrupted"); } } // Examine and throw exception early if there is a problem. StorableIntrospector.examine(type); storage = createStorage(type); mStorageMap.put(type, storage); lock.notifyAll(); } // Storable type lock no longer needed. synchronized (mStorableTypeLockMap) { mStorableTypeLockMap.remove(type); } return storage; }
|
public <S extends Storable> Storage<S> storageFor(Class<S> type) throws MalformedTypeException, SupportException, RepositoryException { Storage storage = mStorageMap.get(type); if (storage != null) { return storage; } Object lock; boolean doCreate; synchronized (mStorableTypeLockMap) { lock = mStorableTypeLockMap.get(type); if (lock != null) { doCreate = false; } else { doCreate = true; lock = new Object(); mStorableTypeLockMap.put(type, lock); } } synchronized (lock) { // Check storage map again before creating new storage. while (true) { storage = mStorageMap.get(type); if (storage != null) { return storage; } if (doCreate) { break; } try { lock.wait(); } catch (InterruptedException e) { throw new RepositoryException("Interrupted"); } } // Examine and throw exception early if there is a problem. StorableIntrospector.examine(type); storage = createStorage(type); mStorageMap.put(type, storage); lock.notifyAll(); } // Storable type lock no longer needed. synchronized (mStorableTypeLockMap) { mStorableTypeLockMap.remove(type); } return storage; }
| 1,109,603
|
public <S extends Storable> Storage<S> storageFor(Class<S> type) throws MalformedTypeException, SupportException, RepositoryException { Storage storage = mStorageMap.get(type); if (storage != null) { return storage; } Object lock; boolean doCreate; synchronized (mStorableTypeLockMap) { lock = mStorableTypeLockMap.get(type); if (lock != null) { doCreate = false; } else { doCreate = true; lock = new Object(); mStorableTypeLockMap.put(type, lock); } } synchronized (lock) { // Check storage map again before creating new storage. while (true) { storage = mStorageMap.get(type); if (storage != null) { return storage; } if (doCreate) { break; } try { lock.wait(); } catch (InterruptedException e) { throw new RepositoryException("Interrupted"); } } // Examine and throw exception early if there is a problem. StorableIntrospector.examine(type); storage = createStorage(type); mStorageMap.put(type, storage); lock.notifyAll(); } // Storable type lock no longer needed. synchronized (mStorableTypeLockMap) { mStorableTypeLockMap.remove(type); } return storage; }
|
public <S extends Storable> Storage<S> storageFor(Class<S> type) throws MalformedTypeException, SupportException, RepositoryException { Storage storage = mStorageMap.get(type); if (storage != null) { return storage; } Object lock; boolean doCreate; synchronized (mStorableTypeLockMap) { lock = mStorableTypeLockMap.get(type); if (lock != null) { doCreate = false; } else { doCreate = true; lock = new Object(); mStorableTypeLockMap.put(type, lock); } } synchronized (lock) { // Check storage map again before creating new storage. while (true) { storage = mStorageMap.get(type); if (storage != null) { return storage; } if (doCreate) { break; } try { lock.wait(); } catch (InterruptedException e) { throw new RepositoryException("Interrupted"); } } // Examine and throw exception early if there is a problem. StorableIntrospector.examine(type); storage = createStorage(type); mStorageMap.put(type, storage); lock.notifyAll(); } // Storable type lock no longer needed. synchronized (mStorableTypeLockMap) { mStorableTypeLockMap.remove(type); } return storage; }
| 1,109,604
|
public void createDatabase( String user, String passwd ) { // Get the database schema XML file InputStream schemaIS = getClass().getClassLoader().getResourceAsStream( "photovault_schema.xml" ); Database dbModel = new DatabaseIO().read( new InputStreamReader( schemaIS ) ); // Create the datasource for accessing this database String driverName = "com.mysql.jdbc.Driver"; String dbUrl = "jdbc:mysql://" + getDbHost() + "/" + getDbName(); DataSource ds = null; if ( instanceType == TYPE_EMBEDDED ) { if ( !embeddedDirectory.exists() ) { embeddedDirectory.mkdirs(); } File derbyDir = new File( embeddedDirectory, "derby" ); File photoDir = new File( embeddedDirectory, "photos"); Volume vol = new Volume( "photos", photoDir.getAbsolutePath() ); addVolume( vol ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); driverName = "org.apache.derby.jdbc.EmbeddedDriver"; dbUrl = "jdbc:derby:photovault;create=true"; EmbeddedDataSource derbyDs = new EmbeddedDataSource(); derbyDs.setDatabaseName( "photovault" ); derbyDs.setCreateDatabase( "create" ); ds = derbyDs; } else { MysqlDataSource mysqlDs = new MysqlDataSource(); mysqlDs.setURL( dbUrl ); mysqlDs.setUser( user ); mysqlDs.setPassword( passwd ); ds = mysqlDs; } Platform platform = PlatformFactory.createNewPlatformInstance( ds ); /* * Do not use delimiters for the database object names in SQWL statements. * This is to avoid case sensitivity problems with SQL92 compliant * databases like Derby - non-delimited identifiers are interpreted as case * insensitive. * * I am not sure if this is the correct way to solve the issue, however, * I am not willing to make a big change of schema definitions either. */ platform.getPlatformInfo().setDelimiterToken( "" ); platform.setUsername( user ); platform.setPassword( passwd ); platform.createTables( dbModel, true, true ); // Insert the seed data to database DataToDatabaseSink sink = new DataToDatabaseSink( platform, dbModel ); DataReader reader = new DataReader(); reader.setModel( dbModel ); reader.setSink( sink ); InputStream seedDataStream = this.getClass().getClassLoader().getResourceAsStream( "photovault_seed_data.xml" ); try { reader.parse( seedDataStream ); } catch (SAXException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } // Create the database // TODO: Since the seed has only 48 significant bits this id is not really an // 128-bit random number!!! Random rnd = new Random(); String idStr = ""; StringBuffer idBuf = new StringBuffer(); for ( int n=0; n < 4; n++ ) { int r = rnd.nextInt(); idBuf.append( Integer.toHexString( r ) ); } idStr = idBuf.toString(); DynaBean dbInfo = dbModel.createDynaBeanFor( "database_info", false ); dbInfo.set( "database_id", idStr ); dbInfo.set( "schema_version", new Integer(3) ); dbInfo.set( "create_time", new Timestamp( System.currentTimeMillis() ) ); platform.insert( dbModel, dbInfo ); }
|
public void createDatabase( String user, String passwd ) { // Get the database schema XML file InputStream schemaIS = getClass().getClassLoader().getResourceAsStream( "photovault_schema.xml" ); Database dbModel = new DatabaseIO().read( new InputStreamReader( schemaIS ) ); // Create the datasource for accessing this database String driverName = "com.mysql.jdbc.Driver"; String dbUrl = "jdbc:mysql://" + getDbHost() + "/" + getDbName(); DataSource ds = null; if ( instanceType == TYPE_EMBEDDED ) { if ( !embeddedDirectory.exists() ) { embeddedDirectory.mkdirs(); } File derbyDir = new File( embeddedDirectory, "derby" ); File photoDir = new File( embeddedDirectory, "photos"); Volume vol = new Volume( "photos", photoDir.getAbsolutePath() ); addVolume( vol ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); driverName = "org.apache.derby.jdbc.EmbeddedDriver"; dbUrl = "jdbc:derby:photovault;create=true"; EmbeddedDataSource derbyDs = new EmbeddedDataSource(); derbyDs.setDatabaseName( "photovault" ); derbyDs.setCreateDatabase( "create" ); ds = derbyDs; } else { MysqlDataSource mysqlDs = new MysqlDataSource(); mysqlDs.setURL( dbUrl ); mysqlDs.setUser( user ); mysqlDs.setPassword( passwd ); ds = mysqlDs; } Platform platform = PlatformFactory.createNewPlatformInstance( ds ); /* * Do not use delimiters for the database object names in SQL statements. * This is to avoid case sensitivity problems with SQL92 compliant * databases like Derby - non-delimited identifiers are interpreted as case * insensitive. * * I am not sure if this is the correct way to solve the issue, however, * I am not willing to make a big change of schema definitions either. */ platform.getPlatformInfo().setDelimiterToken( "" ); platform.setUsername( user ); platform.setPassword( passwd ); platform.createTables( dbModel, true, true ); // Insert the seed data to database DataToDatabaseSink sink = new DataToDatabaseSink( platform, dbModel ); DataReader reader = new DataReader(); reader.setModel( dbModel ); reader.setSink( sink ); InputStream seedDataStream = this.getClass().getClassLoader().getResourceAsStream( "photovault_seed_data.xml" ); try { reader.parse( seedDataStream ); } catch (SAXException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } // Create the database // TODO: Since the seed has only 48 significant bits this id is not really an // 128-bit random number!!! Random rnd = new Random(); String idStr = ""; StringBuffer idBuf = new StringBuffer(); for ( int n=0; n < 4; n++ ) { int r = rnd.nextInt(); idBuf.append( Integer.toHexString( r ) ); } idStr = idBuf.toString(); DynaBean dbInfo = dbModel.createDynaBeanFor( "database_info", false ); dbInfo.set( "database_id", idStr ); dbInfo.set( "schema_version", new Integer(3) ); dbInfo.set( "create_time", new Timestamp( System.currentTimeMillis() ) ); platform.insert( dbModel, dbInfo ); }
| 1,109,606
|
public void doTag(XMLOutput output) throws Exception { String localName = null; int idx = name.indexOf(':'); if (idx >= 0) { localName = name.substring(idx + 1); } else { localName = name; } /** * @todo we should buffer up any SAX events and replay then * inside the startElement/endElement block */ invokeBody(output); output.startElement(namespace, localName, name, attributes); /** @todo we should replay the cached SAX events (if any) here */ output.endElement(namespace, localName, name); attributes.clear(); }
|
public void doTag(XMLOutput output) throws Exception { int idx = name.indexOf(':'); if (idx >= 0) { localName = name.substring(idx + 1); } else { localName = name; } /** * @todo we should buffer up any SAX events and replay then * inside the startElement/endElement block */ invokeBody(output); output.startElement(namespace, localName, name, attributes); /** @todo we should replay the cached SAX events (if any) here */ output.endElement(namespace, localName, name); attributes.clear(); }
| 1,109,607
|
public void doTag(XMLOutput output) throws Exception { String localName = null; int idx = name.indexOf(':'); if (idx >= 0) { localName = name.substring(idx + 1); } else { localName = name; } /** * @todo we should buffer up any SAX events and replay then * inside the startElement/endElement block */ invokeBody(output); output.startElement(namespace, localName, name, attributes); /** @todo we should replay the cached SAX events (if any) here */ output.endElement(namespace, localName, name); attributes.clear(); }
|
public void doTag(XMLOutput output) throws Exception { String localName = null; int idx = name.indexOf(':'); if (idx >= 0) { localName = name.substring(idx + 1); } else { localName = name; } /** * @todo we should buffer up any SAX events and replay then * inside the startElement/endElement block */ invokeBody(output); output.startElement(namespace, localName, name, attributes); /** @todo we should replay the cached SAX events (if any) here */ output.endElement(namespace, localName, name); attributes.clear(); }
| 1,109,608
|
public void doTag(XMLOutput output) throws Exception { String localName = null; int idx = name.indexOf(':'); if (idx >= 0) { localName = name.substring(idx + 1); } else { localName = name; } /** * @todo we should buffer up any SAX events and replay then * inside the startElement/endElement block */ invokeBody(output); output.startElement(namespace, localName, name, attributes); /** @todo we should replay the cached SAX events (if any) here */ output.endElement(namespace, localName, name); attributes.clear(); }
|
public void doTag(XMLOutput output) throws Exception { String localName = null; int idx = name.indexOf(':'); if (idx >= 0) { localName = name.substring(idx + 1); } else { localName = name; } /** * @todo we should buffer up any SAX events and replay then * inside the startElement/endElement block */ invokeBody(output); output.startElement(namespace, localName, name, attributes); /** @todo we should replay the cached SAX events (if any) here */ output.endElement(namespace, localName, name); attributes.clear(); }
| 1,109,609
|
public void setAttributeValue( String name, String value ) { // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value); } }
|
public void setAttributeValue( String name, String value ) throws JellyException { if (outputAttributes) { throw new JellyException( "Cannot set the value of attribute: " + name + " as we have already output the startElement() SAX event" ); } // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### we should be namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value); } }
| 1,109,610
|
public void drop(DropTargetDropEvent e) { hoverTimer.stop(); // Prevent hover timer from doing an unwanted expandPath or collapsePath if (!isDropAcceptable(e)) { e.rejectDrop(); return; } e.acceptDrop(e.getDropAction()); Transferable transferable = e.getTransferable(); DataFlavor[] flavors = transferable.getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++ ) { DataFlavor flavor = flavors[i]; if (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType)) { try { Point pt = e.getLocation(); TreePath pathTarget = tree.getClosestPathForLocation(pt.x, pt.y); PhotoFolder folder = (PhotoFolder) pathTarget.getLastPathComponent(); PhotoCollectionTransferHandler.setLastImportTarget( folder ); PhotoInfo[] photos = (PhotoInfo[])transferable.getTransferData(photoInfoFlavor); for ( int n = 0; n < photos.length; n++ ) { folder.addPhoto( photos[n] ); } break; // No need to check remaining flavors } catch (UnsupportedFlavorException ufe) { System.out.println(ufe); e.dropComplete(false); return; } catch (IOException ioe) { System.out.println(ioe); e.dropComplete(false); return; } } } e.dropComplete(true); }
|
public void drop(DropTargetDropEvent e) { hoverTimer.stop(); // Prevent hover timer from doing an unwanted expandPath or collapsePath if (!isDropAcceptable(e)) { e.rejectDrop(); return; } e.acceptDrop(e.getDropAction()); Transferable transferable = e.getTransferable(); DataFlavor[] flavors = transferable.getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++ ) { DataFlavor flavor = flavors[i]; if (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType)) { try { Point pt = e.getLocation(); TreePath pathTarget = tree.getClosestPathForLocation(pt.x, pt.y); PhotoFolder folder = (PhotoFolder) pathTarget.getLastPathComponent(); PhotoCollectionTransferHandler.setLastImportTarget( folder ); PhotoInfo[] photos = (PhotoInfo[])transferable.getTransferData(photoInfoFlavor); for ( int n = 0; n < photos.length; n++ ) { folder.addPhoto( photos[n] ); } break; // No need to check remaining flavors } catch (UnsupportedFlavorException ufe) { log.warn(ufe); e.dropComplete(false); return; } catch (IOException ioe) { System.out.println(ioe); e.dropComplete(false); return; } } } e.dropComplete(true); }
| 1,109,613
|
public void drop(DropTargetDropEvent e) { hoverTimer.stop(); // Prevent hover timer from doing an unwanted expandPath or collapsePath if (!isDropAcceptable(e)) { e.rejectDrop(); return; } e.acceptDrop(e.getDropAction()); Transferable transferable = e.getTransferable(); DataFlavor[] flavors = transferable.getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++ ) { DataFlavor flavor = flavors[i]; if (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType)) { try { Point pt = e.getLocation(); TreePath pathTarget = tree.getClosestPathForLocation(pt.x, pt.y); PhotoFolder folder = (PhotoFolder) pathTarget.getLastPathComponent(); PhotoCollectionTransferHandler.setLastImportTarget( folder ); PhotoInfo[] photos = (PhotoInfo[])transferable.getTransferData(photoInfoFlavor); for ( int n = 0; n < photos.length; n++ ) { folder.addPhoto( photos[n] ); } break; // No need to check remaining flavors } catch (UnsupportedFlavorException ufe) { System.out.println(ufe); e.dropComplete(false); return; } catch (IOException ioe) { System.out.println(ioe); e.dropComplete(false); return; } } } e.dropComplete(true); }
|
public void drop(DropTargetDropEvent e) { hoverTimer.stop(); // Prevent hover timer from doing an unwanted expandPath or collapsePath if (!isDropAcceptable(e)) { e.rejectDrop(); return; } e.acceptDrop(e.getDropAction()); Transferable transferable = e.getTransferable(); DataFlavor[] flavors = transferable.getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++ ) { DataFlavor flavor = flavors[i]; if (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType)) { try { Point pt = e.getLocation(); TreePath pathTarget = tree.getClosestPathForLocation(pt.x, pt.y); PhotoFolder folder = (PhotoFolder) pathTarget.getLastPathComponent(); PhotoCollectionTransferHandler.setLastImportTarget( folder ); PhotoInfo[] photos = (PhotoInfo[])transferable.getTransferData(photoInfoFlavor); for ( int n = 0; n < photos.length; n++ ) { folder.addPhoto( photos[n] ); } break; // No need to check remaining flavors } catch (UnsupportedFlavorException ufe) { System.out.println(ufe); e.dropComplete(false); return; } catch (IOException ioe) { log.warn(ioe); e.dropComplete(false); return; } } } e.dropComplete(true); }
| 1,109,614
|
public Object getVariable(String name) { Object value = variables.get(name); if ( value == null && getInherit() ) { value = getParent().findVariable( name ); } return value; }
|
public Object getVariable(String name) { Object value = variables.get(name); if ( value == null && isInherit() ) { value = getParent().findVariable( name ); } return value; }
| 1,109,617
|
public void setExport(boolean shouldExport) { this.shouldExport = shouldExport; }
|
public void setExport(boolean shouldExport) { this.shouldExport = shouldExport; }
| 1,109,618
|
public void setInherit(boolean shouldInherit) { this.shouldInherit = shouldInherit; }
|
public void setInherit(boolean shouldInherit) { this.shouldInherit = shouldInherit; }
| 1,109,619
|
public void setVariable(String name, Object value) { if ( getExport() ) { getParent().setVariable( name, value ); return; } if (value == null) { variables.remove(name); } else { variables.put(name, value); } }
|
public void setVariable(String name, Object value) { if ( isExport() ) { getParent().setVariable( name, value ); return; } if (value == null) { variables.remove(name); } else { variables.put(name, value); } }
| 1,109,620
|
public String getFreqString(int i ){ if (Options.getAssocTest() == ASSOC_TRIO){ return ""; } nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); StringBuffer countSB = new StringBuffer(); Haplotype h = (Haplotype) alleles.get(i); double caseSum = 0, controlSum = 0; for (int j = 0; j < alleles.size(); j++){ caseSum += ((Haplotype)alleles.get(j)).getCaseCount(); controlSum += ((Haplotype)alleles.get(j)).getControlCount(); } countSB.append(nf.format(h.getCaseCount()/caseSum)).append(", "); countSB.append(nf.format(h.getControlCount()/controlSum)); return countSB.toString(); }
|
public String getFreqString(int i ){ if (Options.getAssocTest() == ASSOC_TRIO){ return ""; } nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); StringBuffer countSB = new StringBuffer(); Haplotype h = (Haplotype) filteredAlleles.get(i); double caseSum = 0, controlSum = 0; for (int j = 0; j < alleles.size(); j++){ caseSum += ((Haplotype)alleles.get(j)).getCaseCount(); controlSum += ((Haplotype)alleles.get(j)).getControlCount(); } countSB.append(nf.format(h.getCaseCount()/caseSum)).append(", "); countSB.append(nf.format(h.getControlCount()/controlSum)); return countSB.toString(); }
| 1,109,621
|
public JSR160ServerConnection(JMXConnector jmxc ) throws IOException { assert jmxc != null; this.jmxc = jmxc; this.mbeanServer = jmxc.getMBeanServerConnection(); }
|
public JSR160ServerConnection(JMXConnector jmxc, MBeanServerConnection mbeanServer) throws IOException { assert jmxc != null; this.jmxc = jmxc; this.mbeanServer = jmxc.getMBeanServerConnection(); }
| 1,109,622
|
public JSR160ServerConnection(JMXConnector jmxc ) throws IOException { assert jmxc != null; this.jmxc = jmxc; this.mbeanServer = jmxc.getMBeanServerConnection(); }
|
public JSR160ServerConnection(JMXConnector jmxc ) throws IOException { assert jmxc != null; this.jmxc = jmxc; this.mbeanServer = mbeanServer; }
| 1,109,623
|
public void createMBean(String className, ObjectName name, Object[] params, String[] signature){ throw new RuntimeException("Notifications not supported"); }
|
public void createMBean(String className, ObjectName name, Object[] params, String[] signature){ Class[] methodSignature = new Class[]{String.class, javax.management.ObjectName.class, new Object[0].getClass(), new String[0].getClass()}; Object[] methodArgs = new Object[]{className, toJMXObjectName(name), params, signature}; callMBeanServer("createMBean", methodSignature, methodArgs); }
| 1,109,624
|
public void unregisterMBean(ObjectName objectName){ throw new RuntimeException("unregisterMBean not supported"); }
|
public void unregisterMBean(ObjectName objectName){ Class[] methodSignature = new Class[]{javax.management.ObjectName.class}; Object[] methodArgs = new Object[]{toJMXObjectName(objectName)}; callMBeanServer("unregisterMBean", methodSignature, methodArgs); }
| 1,109,625
|
public String getAlleleName(int i) { return ((Haplotype) alleles.get(i)).toString(); }
|
public String getAlleleName(int i) { return ((Haplotype) filteredAlleles.get(i)).toString(); }
| 1,109,626
|
public String getFreq(int j) { double freq = ((Haplotype)alleles.get(j)).getPercentage(); if (freq < 0){ return (""); }else{ nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); return nf.format(freq); } }
|
public String getFreq(int j) { double freq = ((Haplotype)alleles.get(j)).getPercentage(); if (freq < 0){ return (""); }else{ nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); return nf.format(freq); } }
| 1,109,627
|
public String getNumericAlleleName(int i){ return ((Haplotype) alleles.get(i)).toNumericString(); }
|
public String getNumericAlleleName(int i){ return ((Haplotype) filteredAlleles.get(i)).toNumericString(); }
| 1,109,628
|
private void full_em_breakup( byte[][] input_haplos, int[] block_size, Vector affStatus, Vector kidAffStatus, boolean[] haploid) throws HaploViewException{ int num_poss, iter; double total = 0; int block, start_locus, end_locus, biggest_block_size; int num_indivs = 0; int num_blocks = block_size.length; int num_haplos = input_haplos.length; int num_loci = input_haplos[0].length; Recovery tempRec; if (num_loci > MAXLOCI){ throw new HaploViewException("Too many loci in a single block (> "+MAXLOCI+" non-redundant)"); } //figure out the size of the biggest block biggest_block_size=block_size[0]; for (int i=1; i<num_blocks; i++) { if (block_size[i] > biggest_block_size) biggest_block_size=block_size[i]; } num_poss = two_n[biggest_block_size]; data = new OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) data[i]= new OBS(); superdata = new SUPER_OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) superdata[i]= new SUPER_OBS(num_blocks); double[][] hprob = new double[num_blocks][num_poss]; int[][] hlist = new int[num_blocks][num_poss]; int[] num_hlist = new int[num_blocks]; int[] hint = new int[num_poss]; MapWrap probMap = new MapWrap(PSEUDOCOUNT); /* for trio option */ if (Options.getAssocTest() == ASSOC_TRIO) { ambighet = new int[(num_haplos/4)][num_loci]; store_dhet_status(num_haplos,num_loci,input_haplos); } end_locus=-1; //now we loop through the blocks for (block=0; block<num_blocks; block++) { start_locus=end_locus+1; end_locus=start_locus+block_size[block]-1; num_poss=two_n[block_size[block]]; //read_observations initializes the values in data[] (array of OBS) num_indivs=read_observations(num_haplos,num_loci,input_haplos,start_locus,end_locus); total=(double)num_poss; total *= PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (data[i].nposs==1) { tempRec = (Recovery)data[i].poss.elementAt(0); probMap.put(new Long(tempRec.h1), probMap.get(new Long(tempRec.h1)) + 1.0); if (!haploid[i]){ probMap.put(new Long(tempRec.h2), probMap.get(new Long(tempRec.h2)) + 1.0); total+=2.0; }else{ total+=1.0; } } } probMap.normalize(total); // EM LOOP: assign ambiguous data based on p, then re-estimate p iter=0; while (iter<20) { // compute probabilities of each possible observation for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); if(haploid[i]){ tempRec.p = (float)(probMap.get(new Long(tempRec.h1))); }else { tempRec.p = (float)(probMap.get(new Long(tempRec.h1))*probMap.get(new Long(tempRec.h2))); } total+=tempRec.p; } // normalize for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); tempRec.p /= total; } } // re-estimate prob probMap = new MapWrap(1e-10); total=num_poss*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); probMap.put(new Long(tempRec.h1),probMap.get(new Long(tempRec.h1)) + tempRec.p); if (!haploid[i]){ probMap.put(new Long(tempRec.h2),probMap.get(new Long(tempRec.h2)) + tempRec.p); total+=(2.0*(tempRec.p)); }else{ total += tempRec.p; } } } probMap.normalize(total); iter++; } int m=0; for(long j=0;j<num_poss; j++){ hint[(int)j]=-1; if (probMap.get(new Long(j)) > .001) { // printf("haplo %s p = %.4lf\n",haplo_str(j,block_size[block]),prob[j]); hlist[block][m]=(int)j; hprob[block][m]=probMap.get(new Long(j)); hint[(int)j]=m; m++; } } num_hlist[block]=m; // store current block results in super obs structure store_block_haplos(hlist, hprob, hint, block, num_indivs); } /* for each block */ double poss_full=1; for (block=0; block<num_blocks; block++) { poss_full *= num_hlist[block]; } /* LIGATE and finish this mess :) */ fullProbMap = new MapWrap(PSEUDOCOUNT); create_super_haplos(num_indivs,num_blocks,num_hlist); /* run standard EM on supercombos */ /* start prob array with probabilities from full observations */ total = poss_full * PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (superdata[i].nsuper==1) { Long h1 = new Long(superdata[i].superposs[0].h1); Long h2 = new Long(superdata[i].superposs[0].h2); fullProbMap.put(h1,fullProbMap.get(h1) +1.0); if (!haploid[i]){ fullProbMap.put(h2,fullProbMap.get(h2) +1.0); total+=2.0; }else{ total+=1.0; } } } fullProbMap.normalize(total); /* EM LOOP: assign ambiguous data based on p, then re-estimate p */ iter=0; while (iter<20) { /* compute probabilities of each possible observation */ for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<superdata[i].nsuper; k++) { if(haploid[i]){ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))); }else{ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))* fullProbMap.get(new Long(superdata[i].superposs[k].h2))); } total+=superdata[i].superposs[k].p; } /* normalize */ for (int k=0; k<superdata[i].nsuper; k++) { superdata[i].superposs[k].p /= total; } } /* re-estimate prob */ fullProbMap = new MapWrap(1e-10); total=poss_full*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<superdata[i].nsuper; k++) { fullProbMap.put(new Long(superdata[i].superposs[k].h1),fullProbMap.get(new Long(superdata[i].superposs[k].h1)) + superdata[i].superposs[k].p); if(!haploid[i]){ fullProbMap.put(new Long(superdata[i].superposs[k].h2),fullProbMap.get(new Long(superdata[i].superposs[k].h2)) + superdata[i].superposs[k].p); total+=(2.0*superdata[i].superposs[k].p); }else{ total += superdata[i].superposs[k].p; } } } fullProbMap.normalize(total); iter++; } /* we're done - the indices of superprob now have to be decoded to reveal the actual haplotypes they represent */ if(Options.getAssocTest() == ASSOC_TRIO) { kidConsistentCache = new boolean[numFilteredTrios][][]; for(int i=0;i<numFilteredTrios*2;i+=2) { if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ kidConsistentCache[i/2] = new boolean[superdata[i].nsuper][]; for (int n=0; n<superdata[i].nsuper; n++) { kidConsistentCache[i/2][n] = new boolean[superdata[i+1].nsuper]; for (int m=0; m<superdata[i+1].nsuper; m++) { kidConsistentCache[i/2][n][m] = kid_consistent(superdata[i].superposs[n].h1, superdata[i+1].superposs[m].h1,num_blocks, block_size,hlist,num_hlist,i/2,num_loci); } } } } } realAffectedStatus = affStatus; doAssociationTests(affStatus, null, kidAffStatus); Vector haplos_present = new Vector(); Vector haplo_freq= new Vector(); ArrayList keys = new ArrayList(fullProbMap.theMap.keySet()); Collections.sort(keys); Iterator kitr = keys.iterator(); while(kitr.hasNext()) { Object key = kitr.next(); long keyLong = ((Long)key).longValue(); if(fullProbMap.get(key) > .001) { haplos_present.addElement(decode_haplo_str(keyLong,num_blocks,block_size,hlist,num_hlist)); haplo_freq.addElement(new Double(fullProbMap.get(key))); } } double[] freqs = new double[haplo_freq.size()]; for(int j=0;j<haplo_freq.size();j++) { freqs[j] = ((Double)haplo_freq.elementAt(j)).doubleValue(); } this.haplotypes = (int[][])haplos_present.toArray(new int[0][0]); this.frequencies = freqs; /* if (dump_phased_haplos) { if ((fpdump=fopen("emphased.haps","w"))!=NULL) { for (i=0; i<num_indivs; i++) { best=0; for (k=0; k<superdata[i].nsuper; k++) { if (superdata[i].superposs[k].p > superdata[i].superposs[best].p) { best=k; } } h1 = superdata[i].superposs[best].h1; h2 = superdata[i].superposs[best].h2; fprintf(fpdump,"%s\n",decode_haplo_str(h1,num_blocks,block_size,hlist,num_hlist)); fprintf(fpdump,"%s\n",decode_haplo_str(h2,num_blocks,block_size,hlist,num_hlist)); } fclose(fpdump); } } */ //return 0; }
|
private void full_em_breakup( byte[][] input_haplos, int[] block_size, Vector affStatus, Vector kidAffStatus, boolean[] haploid) throws HaploViewException{ int num_poss, iter; double total = 0; int block, start_locus, end_locus, biggest_block_size; int num_indivs = 0; int num_blocks = block_size.length; int num_haplos = input_haplos.length; int num_loci = input_haplos[0].length; Recovery tempRec; if (num_loci > MAXLOCI){ throw new HaploViewException("Too many loci in a single block (> "+MAXLOCI+" non-redundant)"); } //figure out the size of the biggest block biggest_block_size=block_size[0]; for (int i=1; i<num_blocks; i++) { if (block_size[i] > biggest_block_size) biggest_block_size=block_size[i]; } num_poss = two_n[biggest_block_size]; data = new OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) data[i]= new OBS(); superdata = new SUPER_OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) superdata[i]= new SUPER_OBS(num_blocks); double[][] hprob = new double[num_blocks][num_poss]; int[][] hlist = new int[num_blocks][num_poss]; int[] num_hlist = new int[num_blocks]; int[] hint = new int[num_poss]; MapWrap probMap = new MapWrap(PSEUDOCOUNT); /* for trio option */ if (Options.getAssocTest() == ASSOC_TRIO) { ambighet = new int[(num_haplos/4)][num_loci]; store_dhet_status(num_haplos,num_loci,input_haplos); } end_locus=-1; //now we loop through the blocks for (block=0; block<num_blocks; block++) { start_locus=end_locus+1; end_locus=start_locus+block_size[block]-1; num_poss=two_n[block_size[block]]; //read_observations initializes the values in data[] (array of OBS) num_indivs=read_observations(num_haplos,num_loci,input_haplos,start_locus,end_locus); total=(double)num_poss; total *= PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (data[i].nposs==1) { tempRec = (Recovery)data[i].poss.elementAt(0); probMap.put(new Long(tempRec.h1), probMap.get(new Long(tempRec.h1)) + 1.0); if (!haploid[i]){ probMap.put(new Long(tempRec.h2), probMap.get(new Long(tempRec.h2)) + 1.0); total+=2.0; }else{ total+=1.0; } } } probMap.normalize(total); // EM LOOP: assign ambiguous data based on p, then re-estimate p iter=0; while (iter<20) { // compute probabilities of each possible observation for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); if(haploid[i]){ if (tempRec.h1 == tempRec.h2){ tempRec.p = (float)(probMap.get(new Long(tempRec.h1))); }else{ tempRec.p = 0; } }else { tempRec.p = (float)(probMap.get(new Long(tempRec.h1))*probMap.get(new Long(tempRec.h2))); } total+=tempRec.p; } // normalize for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); tempRec.p /= total; } } // re-estimate prob probMap = new MapWrap(1e-10); total=num_poss*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); probMap.put(new Long(tempRec.h1),probMap.get(new Long(tempRec.h1)) + tempRec.p); if (!haploid[i]){ probMap.put(new Long(tempRec.h2),probMap.get(new Long(tempRec.h2)) + tempRec.p); total+=(2.0*(tempRec.p)); }else{ total += tempRec.p; } } } probMap.normalize(total); iter++; } int m=0; for(long j=0;j<num_poss; j++){ hint[(int)j]=-1; if (probMap.get(new Long(j)) > .001) { // printf("haplo %s p = %.4lf\n",haplo_str(j,block_size[block]),prob[j]); hlist[block][m]=(int)j; hprob[block][m]=probMap.get(new Long(j)); hint[(int)j]=m; m++; } } num_hlist[block]=m; // store current block results in super obs structure store_block_haplos(hlist, hprob, hint, block, num_indivs); } /* for each block */ double poss_full=1; for (block=0; block<num_blocks; block++) { poss_full *= num_hlist[block]; } /* LIGATE and finish this mess :) */ fullProbMap = new MapWrap(PSEUDOCOUNT); create_super_haplos(num_indivs,num_blocks,num_hlist); /* run standard EM on supercombos */ /* start prob array with probabilities from full observations */ total = poss_full * PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (superdata[i].nsuper==1) { Long h1 = new Long(superdata[i].superposs[0].h1); Long h2 = new Long(superdata[i].superposs[0].h2); fullProbMap.put(h1,fullProbMap.get(h1) +1.0); if (!haploid[i]){ fullProbMap.put(h2,fullProbMap.get(h2) +1.0); total+=2.0; }else{ total+=1.0; } } } fullProbMap.normalize(total); /* EM LOOP: assign ambiguous data based on p, then re-estimate p */ iter=0; while (iter<20) { /* compute probabilities of each possible observation */ for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<superdata[i].nsuper; k++) { if(haploid[i]){ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))); }else{ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))* fullProbMap.get(new Long(superdata[i].superposs[k].h2))); } total+=superdata[i].superposs[k].p; } /* normalize */ for (int k=0; k<superdata[i].nsuper; k++) { superdata[i].superposs[k].p /= total; } } /* re-estimate prob */ fullProbMap = new MapWrap(1e-10); total=poss_full*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<superdata[i].nsuper; k++) { fullProbMap.put(new Long(superdata[i].superposs[k].h1),fullProbMap.get(new Long(superdata[i].superposs[k].h1)) + superdata[i].superposs[k].p); if(!haploid[i]){ fullProbMap.put(new Long(superdata[i].superposs[k].h2),fullProbMap.get(new Long(superdata[i].superposs[k].h2)) + superdata[i].superposs[k].p); total+=(2.0*superdata[i].superposs[k].p); }else{ total += superdata[i].superposs[k].p; } } } fullProbMap.normalize(total); iter++; } /* we're done - the indices of superprob now have to be decoded to reveal the actual haplotypes they represent */ if(Options.getAssocTest() == ASSOC_TRIO) { kidConsistentCache = new boolean[numFilteredTrios][][]; for(int i=0;i<numFilteredTrios*2;i+=2) { if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ kidConsistentCache[i/2] = new boolean[superdata[i].nsuper][]; for (int n=0; n<superdata[i].nsuper; n++) { kidConsistentCache[i/2][n] = new boolean[superdata[i+1].nsuper]; for (int m=0; m<superdata[i+1].nsuper; m++) { kidConsistentCache[i/2][n][m] = kid_consistent(superdata[i].superposs[n].h1, superdata[i+1].superposs[m].h1,num_blocks, block_size,hlist,num_hlist,i/2,num_loci); } } } } } realAffectedStatus = affStatus; doAssociationTests(affStatus, null, kidAffStatus); Vector haplos_present = new Vector(); Vector haplo_freq= new Vector(); ArrayList keys = new ArrayList(fullProbMap.theMap.keySet()); Collections.sort(keys); Iterator kitr = keys.iterator(); while(kitr.hasNext()) { Object key = kitr.next(); long keyLong = ((Long)key).longValue(); if(fullProbMap.get(key) > .001) { haplos_present.addElement(decode_haplo_str(keyLong,num_blocks,block_size,hlist,num_hlist)); haplo_freq.addElement(new Double(fullProbMap.get(key))); } } double[] freqs = new double[haplo_freq.size()]; for(int j=0;j<haplo_freq.size();j++) { freqs[j] = ((Double)haplo_freq.elementAt(j)).doubleValue(); } this.haplotypes = (int[][])haplos_present.toArray(new int[0][0]); this.frequencies = freqs; /* if (dump_phased_haplos) { if ((fpdump=fopen("emphased.haps","w"))!=NULL) { for (i=0; i<num_indivs; i++) { best=0; for (k=0; k<superdata[i].nsuper; k++) { if (superdata[i].superposs[k].p > superdata[i].superposs[best].p) { best=k; } } h1 = superdata[i].superposs[best].h1; h2 = superdata[i].superposs[best].h2; fprintf(fpdump,"%s\n",decode_haplo_str(h1,num_blocks,block_size,hlist,num_hlist)); fprintf(fpdump,"%s\n",decode_haplo_str(h2,num_blocks,block_size,hlist,num_hlist)); } fclose(fpdump); } } */ //return 0; }
| 1,109,629
|
private void full_em_breakup( byte[][] input_haplos, int[] block_size, Vector affStatus, Vector kidAffStatus, boolean[] haploid) throws HaploViewException{ int num_poss, iter; double total = 0; int block, start_locus, end_locus, biggest_block_size; int num_indivs = 0; int num_blocks = block_size.length; int num_haplos = input_haplos.length; int num_loci = input_haplos[0].length; Recovery tempRec; if (num_loci > MAXLOCI){ throw new HaploViewException("Too many loci in a single block (> "+MAXLOCI+" non-redundant)"); } //figure out the size of the biggest block biggest_block_size=block_size[0]; for (int i=1; i<num_blocks; i++) { if (block_size[i] > biggest_block_size) biggest_block_size=block_size[i]; } num_poss = two_n[biggest_block_size]; data = new OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) data[i]= new OBS(); superdata = new SUPER_OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) superdata[i]= new SUPER_OBS(num_blocks); double[][] hprob = new double[num_blocks][num_poss]; int[][] hlist = new int[num_blocks][num_poss]; int[] num_hlist = new int[num_blocks]; int[] hint = new int[num_poss]; MapWrap probMap = new MapWrap(PSEUDOCOUNT); /* for trio option */ if (Options.getAssocTest() == ASSOC_TRIO) { ambighet = new int[(num_haplos/4)][num_loci]; store_dhet_status(num_haplos,num_loci,input_haplos); } end_locus=-1; //now we loop through the blocks for (block=0; block<num_blocks; block++) { start_locus=end_locus+1; end_locus=start_locus+block_size[block]-1; num_poss=two_n[block_size[block]]; //read_observations initializes the values in data[] (array of OBS) num_indivs=read_observations(num_haplos,num_loci,input_haplos,start_locus,end_locus); total=(double)num_poss; total *= PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (data[i].nposs==1) { tempRec = (Recovery)data[i].poss.elementAt(0); probMap.put(new Long(tempRec.h1), probMap.get(new Long(tempRec.h1)) + 1.0); if (!haploid[i]){ probMap.put(new Long(tempRec.h2), probMap.get(new Long(tempRec.h2)) + 1.0); total+=2.0; }else{ total+=1.0; } } } probMap.normalize(total); // EM LOOP: assign ambiguous data based on p, then re-estimate p iter=0; while (iter<20) { // compute probabilities of each possible observation for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); if(haploid[i]){ tempRec.p = (float)(probMap.get(new Long(tempRec.h1))); }else { tempRec.p = (float)(probMap.get(new Long(tempRec.h1))*probMap.get(new Long(tempRec.h2))); } total+=tempRec.p; } // normalize for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); tempRec.p /= total; } } // re-estimate prob probMap = new MapWrap(1e-10); total=num_poss*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); probMap.put(new Long(tempRec.h1),probMap.get(new Long(tempRec.h1)) + tempRec.p); if (!haploid[i]){ probMap.put(new Long(tempRec.h2),probMap.get(new Long(tempRec.h2)) + tempRec.p); total+=(2.0*(tempRec.p)); }else{ total += tempRec.p; } } } probMap.normalize(total); iter++; } int m=0; for(long j=0;j<num_poss; j++){ hint[(int)j]=-1; if (probMap.get(new Long(j)) > .001) { // printf("haplo %s p = %.4lf\n",haplo_str(j,block_size[block]),prob[j]); hlist[block][m]=(int)j; hprob[block][m]=probMap.get(new Long(j)); hint[(int)j]=m; m++; } } num_hlist[block]=m; // store current block results in super obs structure store_block_haplos(hlist, hprob, hint, block, num_indivs); } /* for each block */ double poss_full=1; for (block=0; block<num_blocks; block++) { poss_full *= num_hlist[block]; } /* LIGATE and finish this mess :) */ fullProbMap = new MapWrap(PSEUDOCOUNT); create_super_haplos(num_indivs,num_blocks,num_hlist); /* run standard EM on supercombos */ /* start prob array with probabilities from full observations */ total = poss_full * PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (superdata[i].nsuper==1) { Long h1 = new Long(superdata[i].superposs[0].h1); Long h2 = new Long(superdata[i].superposs[0].h2); fullProbMap.put(h1,fullProbMap.get(h1) +1.0); if (!haploid[i]){ fullProbMap.put(h2,fullProbMap.get(h2) +1.0); total+=2.0; }else{ total+=1.0; } } } fullProbMap.normalize(total); /* EM LOOP: assign ambiguous data based on p, then re-estimate p */ iter=0; while (iter<20) { /* compute probabilities of each possible observation */ for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<superdata[i].nsuper; k++) { if(haploid[i]){ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))); }else{ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))* fullProbMap.get(new Long(superdata[i].superposs[k].h2))); } total+=superdata[i].superposs[k].p; } /* normalize */ for (int k=0; k<superdata[i].nsuper; k++) { superdata[i].superposs[k].p /= total; } } /* re-estimate prob */ fullProbMap = new MapWrap(1e-10); total=poss_full*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<superdata[i].nsuper; k++) { fullProbMap.put(new Long(superdata[i].superposs[k].h1),fullProbMap.get(new Long(superdata[i].superposs[k].h1)) + superdata[i].superposs[k].p); if(!haploid[i]){ fullProbMap.put(new Long(superdata[i].superposs[k].h2),fullProbMap.get(new Long(superdata[i].superposs[k].h2)) + superdata[i].superposs[k].p); total+=(2.0*superdata[i].superposs[k].p); }else{ total += superdata[i].superposs[k].p; } } } fullProbMap.normalize(total); iter++; } /* we're done - the indices of superprob now have to be decoded to reveal the actual haplotypes they represent */ if(Options.getAssocTest() == ASSOC_TRIO) { kidConsistentCache = new boolean[numFilteredTrios][][]; for(int i=0;i<numFilteredTrios*2;i+=2) { if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ kidConsistentCache[i/2] = new boolean[superdata[i].nsuper][]; for (int n=0; n<superdata[i].nsuper; n++) { kidConsistentCache[i/2][n] = new boolean[superdata[i+1].nsuper]; for (int m=0; m<superdata[i+1].nsuper; m++) { kidConsistentCache[i/2][n][m] = kid_consistent(superdata[i].superposs[n].h1, superdata[i+1].superposs[m].h1,num_blocks, block_size,hlist,num_hlist,i/2,num_loci); } } } } } realAffectedStatus = affStatus; doAssociationTests(affStatus, null, kidAffStatus); Vector haplos_present = new Vector(); Vector haplo_freq= new Vector(); ArrayList keys = new ArrayList(fullProbMap.theMap.keySet()); Collections.sort(keys); Iterator kitr = keys.iterator(); while(kitr.hasNext()) { Object key = kitr.next(); long keyLong = ((Long)key).longValue(); if(fullProbMap.get(key) > .001) { haplos_present.addElement(decode_haplo_str(keyLong,num_blocks,block_size,hlist,num_hlist)); haplo_freq.addElement(new Double(fullProbMap.get(key))); } } double[] freqs = new double[haplo_freq.size()]; for(int j=0;j<haplo_freq.size();j++) { freqs[j] = ((Double)haplo_freq.elementAt(j)).doubleValue(); } this.haplotypes = (int[][])haplos_present.toArray(new int[0][0]); this.frequencies = freqs; /* if (dump_phased_haplos) { if ((fpdump=fopen("emphased.haps","w"))!=NULL) { for (i=0; i<num_indivs; i++) { best=0; for (k=0; k<superdata[i].nsuper; k++) { if (superdata[i].superposs[k].p > superdata[i].superposs[best].p) { best=k; } } h1 = superdata[i].superposs[best].h1; h2 = superdata[i].superposs[best].h2; fprintf(fpdump,"%s\n",decode_haplo_str(h1,num_blocks,block_size,hlist,num_hlist)); fprintf(fpdump,"%s\n",decode_haplo_str(h2,num_blocks,block_size,hlist,num_hlist)); } fclose(fpdump); } } */ //return 0; }
|
private void full_em_breakup( byte[][] input_haplos, int[] block_size, Vector affStatus, Vector kidAffStatus, boolean[] haploid) throws HaploViewException{ int num_poss, iter; double total = 0; int block, start_locus, end_locus, biggest_block_size; int num_indivs = 0; int num_blocks = block_size.length; int num_haplos = input_haplos.length; int num_loci = input_haplos[0].length; Recovery tempRec; if (num_loci > MAXLOCI){ throw new HaploViewException("Too many loci in a single block (> "+MAXLOCI+" non-redundant)"); } //figure out the size of the biggest block biggest_block_size=block_size[0]; for (int i=1; i<num_blocks; i++) { if (block_size[i] > biggest_block_size) biggest_block_size=block_size[i]; } num_poss = two_n[biggest_block_size]; data = new OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) data[i]= new OBS(); superdata = new SUPER_OBS[num_haplos/2]; for (int i=0; i<num_haplos/2; i++) superdata[i]= new SUPER_OBS(num_blocks); double[][] hprob = new double[num_blocks][num_poss]; int[][] hlist = new int[num_blocks][num_poss]; int[] num_hlist = new int[num_blocks]; int[] hint = new int[num_poss]; MapWrap probMap = new MapWrap(PSEUDOCOUNT); /* for trio option */ if (Options.getAssocTest() == ASSOC_TRIO) { ambighet = new int[(num_haplos/4)][num_loci]; store_dhet_status(num_haplos,num_loci,input_haplos); } end_locus=-1; //now we loop through the blocks for (block=0; block<num_blocks; block++) { start_locus=end_locus+1; end_locus=start_locus+block_size[block]-1; num_poss=two_n[block_size[block]]; //read_observations initializes the values in data[] (array of OBS) num_indivs=read_observations(num_haplos,num_loci,input_haplos,start_locus,end_locus); total=(double)num_poss; total *= PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (data[i].nposs==1) { tempRec = (Recovery)data[i].poss.elementAt(0); probMap.put(new Long(tempRec.h1), probMap.get(new Long(tempRec.h1)) + 1.0); if (!haploid[i]){ probMap.put(new Long(tempRec.h2), probMap.get(new Long(tempRec.h2)) + 1.0); total+=2.0; }else{ total+=1.0; } } } probMap.normalize(total); // EM LOOP: assign ambiguous data based on p, then re-estimate p iter=0; while (iter<20) { // compute probabilities of each possible observation for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); if(haploid[i]){ tempRec.p = (float)(probMap.get(new Long(tempRec.h1))); }else { tempRec.p = (float)(probMap.get(new Long(tempRec.h1))*probMap.get(new Long(tempRec.h2))); } total+=tempRec.p; } // normalize for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); tempRec.p /= total; } } // re-estimate prob probMap = new MapWrap(1e-10); total=num_poss*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<data[i].nposs; k++) { tempRec = (Recovery) data[i].poss.elementAt(k); probMap.put(new Long(tempRec.h1),probMap.get(new Long(tempRec.h1)) + tempRec.p); if (!haploid[i]){ probMap.put(new Long(tempRec.h2),probMap.get(new Long(tempRec.h2)) + tempRec.p); total+=(2.0*(tempRec.p)); }else{ total += tempRec.p; } } } probMap.normalize(total); iter++; } int m=0; for(long j=0;j<num_poss; j++){ hint[(int)j]=-1; if (probMap.get(new Long(j)) > .001) { // printf("haplo %s p = %.4lf\n",haplo_str(j,block_size[block]),prob[j]); hlist[block][m]=(int)j; hprob[block][m]=probMap.get(new Long(j)); hint[(int)j]=m; m++; } } num_hlist[block]=m; // store current block results in super obs structure store_block_haplos(hlist, hprob, hint, block, num_indivs); } /* for each block */ double poss_full=1; for (block=0; block<num_blocks; block++) { poss_full *= num_hlist[block]; } /* LIGATE and finish this mess :) */ fullProbMap = new MapWrap(PSEUDOCOUNT); create_super_haplos(num_indivs,num_blocks,num_hlist); /* run standard EM on supercombos */ /* start prob array with probabilities from full observations */ total = poss_full * PSEUDOCOUNT; /* starting prob is phase known haps + 0.1 (PSEUDOCOUNT) count of every haplotype - i.e., flat when nothing is known, close to phase known if a great deal is known */ for (int i=0; i<num_indivs; i++) { if (superdata[i].nsuper==1) { Long h1 = new Long(superdata[i].superposs[0].h1); Long h2 = new Long(superdata[i].superposs[0].h2); fullProbMap.put(h1,fullProbMap.get(h1) +1.0); if (!haploid[i]){ fullProbMap.put(h2,fullProbMap.get(h2) +1.0); total+=2.0; }else{ total+=1.0; } } } fullProbMap.normalize(total); /* EM LOOP: assign ambiguous data based on p, then re-estimate p */ iter=0; while (iter<20) { /* compute probabilities of each possible observation */ for (int i=0; i<num_indivs; i++) { total=0.0; for (int k=0; k<superdata[i].nsuper; k++) { if(haploid[i]){ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))); }else{ superdata[i].superposs[k].p = (float) (fullProbMap.get(new Long(superdata[i].superposs[k].h1))* fullProbMap.get(new Long(superdata[i].superposs[k].h2))); } total+=superdata[i].superposs[k].p; } /* normalize */ for (int k=0; k<superdata[i].nsuper; k++) { superdata[i].superposs[k].p /= total; } } /* re-estimate prob */ fullProbMap = new MapWrap(1e-10); total=poss_full*1e-10; for (int i=0; i<num_indivs; i++) { for (int k=0; k<superdata[i].nsuper; k++) { fullProbMap.put(new Long(superdata[i].superposs[k].h1),fullProbMap.get(new Long(superdata[i].superposs[k].h1)) + superdata[i].superposs[k].p); if(!haploid[i]){ fullProbMap.put(new Long(superdata[i].superposs[k].h2),fullProbMap.get(new Long(superdata[i].superposs[k].h2)) + superdata[i].superposs[k].p); total+=(2.0*superdata[i].superposs[k].p); }else{ total += superdata[i].superposs[k].p; } } } fullProbMap.normalize(total); iter++; } /* we're done - the indices of superprob now have to be decoded to reveal the actual haplotypes they represent */ if(Options.getAssocTest() == ASSOC_TRIO) { kidConsistentCache = new boolean[numFilteredTrios][][]; for(int i=0;i<numFilteredTrios*2;i+=2) { if (((Integer)kidAffStatus.elementAt(i)).intValue() == 2){ kidConsistentCache[i/2] = new boolean[superdata[i].nsuper][]; for (int n=0; n<superdata[i].nsuper; n++) { kidConsistentCache[i/2][n] = new boolean[superdata[i+1].nsuper]; for (int m=0; m<superdata[i+1].nsuper; m++) { kidConsistentCache[i/2][n][m] = kid_consistent(superdata[i].superposs[n].h1, superdata[i+1].superposs[m].h1,num_blocks, block_size,hlist,num_hlist,i/2,num_loci); } } } } } realAffectedStatus = affStatus; doAssociationTests(affStatus, null, kidAffStatus); Vector haplos_present = new Vector(); Vector haplo_freq= new Vector(); ArrayList keys = new ArrayList(fullProbMap.theMap.keySet()); Collections.sort(keys); Iterator kitr = keys.iterator(); while(kitr.hasNext()) { Object key = kitr.next(); long keyLong = ((Long)key).longValue(); if(fullProbMap.get(key) > .001) { haplos_present.addElement(decode_haplo_str(keyLong,num_blocks,block_size,hlist,num_hlist)); haplo_freq.addElement(new Double(fullProbMap.get(key))); } } double[] freqs = new double[haplo_freq.size()]; for(int j=0;j<haplo_freq.size();j++) { freqs[j] = ((Double)haplo_freq.elementAt(j)).doubleValue(); } this.haplotypes = (int[][])haplos_present.toArray(new int[0][0]); this.frequencies = freqs; /* if (dump_phased_haplos) { if ((fpdump=fopen("emphased.haps","w"))!=NULL) { for (i=0; i<num_indivs; i++) { best=0; for (k=0; k<superdata[i].nsuper; k++) { if (superdata[i].superposs[k].p > superdata[i].superposs[best].p) { best=k; } } h1 = superdata[i].superposs[best].h1; h2 = superdata[i].superposs[best].h2; fprintf(fpdump,"%s\n",decode_haplo_str(h1,num_blocks,block_size,hlist,num_hlist)); fprintf(fpdump,"%s\n",decode_haplo_str(h2,num_blocks,block_size,hlist,num_hlist)); } fclose(fpdump); } } */ //return 0; }
| 1,109,630
|
public void zeroOutMarker(int i){ byte zeroArray[] = {0,0}; this.markers.set(i, zeroArray); }
|
public void zeroOutMarker(int i){ byte zeroArray[] = {0,0}; this.markers.set(i, zeroArray); }
| 1,109,633
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Project project = getProject(); // custom Ant tags if ( name.equals("fileScanner") ) { Tag tag = new FileScannerTag(new FileScanner(project)); return TagScript.newInstance(tag); } AntTag tag = new AntTag( getProject(), name ); if ( name.equals( "echo" ) ) { tag.setTrim(false); } return TagScript.newInstance(tag); }
|
public TagScript createTagScript(final String name, Attributes attributes) throws Exception { Project project = getProject(); // custom Ant tags if ( name.equals("fileScanner") ) { Tag tag = new FileScannerTag(new FileScanner(project)); return TagScript.newInstance(tag); } AntTag tag = new AntTag( getProject(), name ); if ( name.equals( "echo" ) ) { tag.setTrim(false); } return TagScript.newInstance(tag); }
| 1,109,634
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Project project = getProject(); // custom Ant tags if ( name.equals("fileScanner") ) { Tag tag = new FileScannerTag(new FileScanner(project)); return TagScript.newInstance(tag); } AntTag tag = new AntTag( getProject(), name ); if ( name.equals( "echo" ) ) { tag.setTrim(false); } return TagScript.newInstance(tag); }
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Project project = getProject(); // custom Ant tags if ( name.equals("fileScanner") ) { Tag tag = new FileScannerTag(new FileScanner(project)); return TagScript.newInstance(tag); } AntTag tag = new AntTag( getProject(), name ); if ( name.equals( "echo" ) ) { tag.setTrim(false); } return TagScript.newInstance(tag); }
| 1,109,635
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Project project = getProject(); // custom Ant tags if ( name.equals("fileScanner") ) { Tag tag = new FileScannerTag(new FileScanner(project)); return TagScript.newInstance(tag); } AntTag tag = new AntTag( getProject(), name ); if ( name.equals( "echo" ) ) { tag.setTrim(false); } return TagScript.newInstance(tag); }
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Project project = getProject(); // custom Ant tags if ( name.equals("fileScanner") ) { Tag tag = new FileScannerTag(new FileScanner(project)); return TagScript.newInstance(tag); } AntTag tag = new AntTag( getProject(), name ); if ( name.equals( "echo" ) ) { tag.setTrim(false); } return TagScript.newInstance(tag); }
| 1,109,636
|
public JeezTagLibrary() { this( AntTagLibrary.createProject() ); }
|
public JeezTagLibrary() { this.antTagLib = new AntTagLibrary(); }
| 1,109,637
|
public TagScript createTagScript(String name, Attributes attrs) throws Exception { TagScript script = super.createTagScript( name, attrs ); if ( script == null ) { // script = this.coreTagLib.createTagScript( name, attrs ); if ( script == null ) { script = this.werkzTagLib.createTagScript( name, attrs ); if ( script == null ) { if ( isRuntimeTask( name ) ) { if ( ! project.getTaskDefinitions().containsKey( name ) ) { script = this.antTagLib.createRuntimeTaskTagScript( name, attrs ); } else { this.runtimeTasks.remove( name ); } } if ( script == null ) { script = this.antTagLib.createTagScript( name, attrs ); } if ( name.equals( "taskdef" ) ) { addRuntimeTask( attrs.getValue( "name" ) ); } } } } return script; }
|
public TagScript createTagScript(String name, Attributes attrs) throws Exception { TagScript script = super.createTagScript( name, attrs ); if ( script == null ) { // script = this.coreTagLib.createTagScript( name, attrs ); if ( script == null ) { script = this.werkzTagLib.createTagScript( name, attrs ); if ( script == null ) { if ( isRuntimeTask( name ) ) { if ( ! project.getTaskDefinitions().containsKey( name ) ) { script = this.antTagLib.createRuntimeTaskTagScript( name, attrs ); } else { this.runtimeTasks.remove( name ); } } if ( script == null ) { script = this.antTagLib.createTagScript( name, attrs ); } if ( name.equals( "taskdef" ) ) { addRuntimeTask( attrs.getValue( "name" ) ); } } } } return script; }
| 1,109,638
|
public TagScript createTagScript(String name, Attributes attrs) throws Exception { TagScript script = super.createTagScript( name, attrs ); if ( script == null ) { // script = this.coreTagLib.createTagScript( name, attrs ); if ( script == null ) { script = this.werkzTagLib.createTagScript( name, attrs ); if ( script == null ) { if ( isRuntimeTask( name ) ) { if ( ! project.getTaskDefinitions().containsKey( name ) ) { script = this.antTagLib.createRuntimeTaskTagScript( name, attrs ); } else { this.runtimeTasks.remove( name ); } } if ( script == null ) { script = this.antTagLib.createTagScript( name, attrs ); } if ( name.equals( "taskdef" ) ) { addRuntimeTask( attrs.getValue( "name" ) ); } } } } return script; }
|
public TagScript createTagScript(String name, Attributes attrs) throws Exception { TagScript script = super.createTagScript( name, attrs ); if ( script == null ) { // script = this.coreTagLib.createTagScript( name, attrs ); if ( script == null ) { script = this.werkzTagLib.createTagScript( name, attrs ); if ( script == null ) { if ( isRuntimeTask( name ) ) { if ( ! project.getTaskDefinitions().containsKey( name ) ) { script = this.antTagLib.createRuntimeTaskTagScript( name, attrs ); } else { this.runtimeTasks.remove( name ); } } if ( script == null ) { script = this.antTagLib.createTagScript( name, attrs ); } if ( name.equals( "taskdef" ) ) { addRuntimeTask( attrs.getValue( "name" ) ); } } } } return script; }
| 1,109,640
|
public TagScript createTagScript(String name, Attributes attrs) throws Exception { TagScript script = super.createTagScript( name, attrs ); if ( script == null ) { // script = this.coreTagLib.createTagScript( name, attrs ); if ( script == null ) { script = this.werkzTagLib.createTagScript( name, attrs ); if ( script == null ) { if ( isRuntimeTask( name ) ) { if ( ! project.getTaskDefinitions().containsKey( name ) ) { script = this.antTagLib.createRuntimeTaskTagScript( name, attrs ); } else { this.runtimeTasks.remove( name ); } } if ( script == null ) { script = this.antTagLib.createTagScript( name, attrs ); } if ( name.equals( "taskdef" ) ) { addRuntimeTask( attrs.getValue( "name" ) ); } } } } return script; }
|
public TagScript createTagScript(String name, Attributes attrs) throws Exception { TagScript script = super.createTagScript( name, attrs ); if ( script == null ) { // script = this.coreTagLib.createTagScript( name, attrs ); if ( script == null ) { script = this.werkzTagLib.createTagScript( name, attrs ); if ( script == null ) { if ( isRuntimeTask( name ) ) { if ( ! project.getTaskDefinitions().containsKey( name ) ) { script = this.antTagLib.createRuntimeTaskTagScript( name, attrs ); } else { this.runtimeTasks.remove( name ); } } if ( script == null ) { script = this.antTagLib.createTagScript( name, attrs ); } if ( name.equals( "taskdef" ) ) { addRuntimeTask( attrs.getValue( "name" ) ); } } } } return script; }
| 1,109,641
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Object value = templates.get(name); if ( value instanceof Script ) { Script template = (Script) value; DynamicTag tag = new DynamicTag(template); // XXXX: somehow we should find the template's // <invokeBody> tag and associate it with this instance return new DynaTagScript(tag); } else if ( value instanceof DynaTag ) { DynaTag tag = (DynaTag) value; return new DynaTagScript(tag); } return null; }
|
public TagScript createTagScript(final String name, Attributes attributes) throws Exception { Object value = templates.get(name); if ( value instanceof Script ) { Script template = (Script) value; DynamicTag tag = new DynamicTag(template); // XXXX: somehow we should find the template's // <invokeBody> tag and associate it with this instance return new DynaTagScript(tag); } else if ( value instanceof DynaTag ) { DynaTag tag = (DynaTag) value; return new DynaTagScript(tag); } return null; }
| 1,109,642
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Object value = templates.get(name); if ( value instanceof Script ) { Script template = (Script) value; DynamicTag tag = new DynamicTag(template); // XXXX: somehow we should find the template's // <invokeBody> tag and associate it with this instance return new DynaTagScript(tag); } else if ( value instanceof DynaTag ) { DynaTag tag = (DynaTag) value; return new DynaTagScript(tag); } return null; }
|
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Object value = templates.get(name); if ( value instanceof Script ) { Script template = (Script) value; DynamicTag tag = new DynamicTag(template); // XXXX: somehow we should find the template's // <invokeBody> tag and associate it with this instance return new DynaTagScript(tag); } else if ( value instanceof DynaTag ) { DynaTag tag = (DynaTag) value; return new DynaTagScript(tag); } return null; }
| 1,109,643
|
public void setDisplayThresh(int amount) { parent.displayThresh = amount; parent.adjustDisplay(); }
|
public void setDisplayThresh(int amount) { parent.displayThresh = amount; parent.adjustDisplay(); }
| 1,109,644
|
public void testSetDisplayName() { CountingPropertyChangeListener l = new CountingPropertyChangeListener(); ds.addPropertyChangeListener(l); ds.setDisplayName("test"); assertEquals(1, l.getPropertyChangeCount()); assertEquals("displayName", l.getLastPropertyChange()); assertEquals("test", ds.getDisplayName()); }
|
public void testSetDisplayName() { CountingPropertyChangeListener l = new CountingPropertyChangeListener(); ds.addPropertyChangeListener(l); ds.setDisplayName("test"); assertEquals(1, l.getPropertyChangeCount()); assertEquals("name", l.getLastPropertyChange()); assertEquals("test", ds.getDisplayName()); }
| 1,109,646
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
|
public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
| 1,109,649
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
| 1,109,650
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
| 1,109,651
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
| 1,109,653
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
| 1,109,654
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
| 1,109,655
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30, shifts[1]+(x+1)*30); } }
|
public void dPrimeDraw(String[][] table, Graphics g){ int scale = table.length*30; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", shifts[0], shifts[1]); //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30) ,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } }
| 1,109,656
|
public Dimension dPrimeGetPreferredSize(int size){ return new Dimension(size*30, size*30); }
|
public Dimension dPrimeGetPreferredSize(int size){ return new Dimension(size*30, size*30); }
| 1,109,657
|
public Hashtable getProperties() { Hashtable h = new Hashtable(); for (Iterator i = this.context.getVariableNames(); i.hasNext(); ) { String name = (String) i.next(); Object value = this.context.getVariable(name); if (value != null) { h.put(name, value); } } return h; }
|
public Hashtable getProperties() { Hashtable h = new Hashtable(); for (Iterator i = this.context.getVariableNames(); i.hasNext(); ) { String name = (String) i.next(); Object value = this.context.getVariable(name); if (value != null) { h.put(name, value.toString()); } } return h; }
| 1,109,658
|
public ArchitectDataSource() { properties = new HashMap(); }
|
public ArchitectDataSource() { properties = new HashMap<String,String>(); }
| 1,109,659
|
public String get(String key) { return (String) properties.get(key); }
|
public String get(String key) { return properties.get(key); }
| 1,109,660
|
public String getOdbcDsn() { return (String) properties.get(PL_DSN); }
|
public String getOdbcDsn() { return properties.get(PL_DSN); }
| 1,109,661
|
protected PropertyChangeSupport getPcs() { if (pcs == null) pcs = new PropertyChangeSupport(this); return pcs; }
|
private PropertyChangeSupport getPcs() { if (pcs == null) pcs = new PropertyChangeSupport(this); return pcs; }
| 1,109,662
|
public String getPlDbType() { return (String) properties.get(PL_TYPE); }
|
public String getPlDbType() { return properties.get(PL_TYPE); }
| 1,109,663
|
public String getPlSchema() { return (String) properties.get(PL_SCHEMA_OWNER); }
|
public String getPlSchema() { return properties.get(PL_SCHEMA_OWNER); }
| 1,109,664
|
public Map getPropertiesMap() { return properties; }
|
public Map getPropertiesMap() { return properties; }
| 1,109,665
|
private void setWindowImage(Window window, Image image) { Window.setDefaultImage(image); }
|
private void setWindowImage(Window window, Image image) { window.getShell().setImage(image); }
| 1,109,666
|
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 if (parent instanceof Decorations) { Decorations item = (Decorations) parent; item.setImage(image); } else { throw new JellyTagException("This tag must be nested inside a <label>, <button> or <item> tag"); } }
|
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 or a Window"); } 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 if (parent instanceof Decorations) { Decorations item = (Decorations) parent; item.setImage(image); } else { throw new JellyTagException("This tag must be nested inside a <label>, <button> or <item> tag"); } }
| 1,109,667
|
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 if (parent instanceof Decorations) { Decorations item = (Decorations) parent; item.setImage(image); } else { throw new JellyTagException("This tag must be nested inside a <label>, <button> or <item> tag"); } }
|
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"); } 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 if (parent instanceof Decorations) { Decorations item = (Decorations) parent; item.setImage(image); } else { throw new JellyTagException("This tag must be nested inside a <label>, <button> or <item> tag"); } }
| 1,109,668
|
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 if (parent instanceof Decorations) { Decorations item = (Decorations) parent; item.setImage(image); } else { throw new JellyTagException("This tag must be nested inside a <label>, <button> or <item> tag"); } }
|
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 if (parent instanceof Decorations) { Decorations item = (Decorations) parent; item.setImage(image); } else { throw new JellyTagException("This tag must be nested inside a <label>, <button> or <item> tag"); } }
| 1,109,669
|
public HaploView(){ try{ fc = new JFileChooser(System.getProperty("user.dir")); }catch(NullPointerException n){ try{ UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); fc = new JFileChooser(System.getProperty("user.dir")); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e){ } } //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); analysisItem = new JMenuItem(READ_ANALYSIS_TRACK); setAccelerator(analysisItem, 'A', false); analysisItem.addActionListener(this); analysisItem.setEnabled(false); fileMenu.add(analysisItem); blocksItem = new JMenuItem(READ_BLOCKS_FILE); setAccelerator(blocksItem, 'B', false); blocksItem.addActionListener(this); blocksItem.setEnabled(false); fileMenu.add(blocksItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); fileMenu.setMnemonic(KeyEvent.VK_F); menuItem = new JMenuItem("Quit"); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu displayMenu = new JMenu("Display"); displayMenu.setMnemonic(KeyEvent.VK_D); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); viewMenuItems[i].setEnabled(false); group.add(viewMenuItems[i]); } displayMenu.addSeparator(); //a submenu ButtonGroup zg = new ButtonGroup(); JMenu zoomMenu = new JMenu("LD zoom"); zoomMenu.setMnemonic(KeyEvent.VK_Z); zoomMenuItems = new JRadioButtonMenuItem[zoomItems.length]; for (int i = 0; i < zoomItems.length; i++){ zoomMenuItems[i] = new JRadioButtonMenuItem(zoomItems[i], i==0); zoomMenuItems[i].addActionListener(this); zoomMenuItems[i].setActionCommand("zoom" + i); zoomMenu.add(zoomMenuItems[i]); zg.add(zoomMenuItems[i]); } displayMenu.add(zoomMenu); //another submenu ButtonGroup cg = new ButtonGroup(); JMenu colorMenu = new JMenu("LD color scheme"); colorMenu.setMnemonic(KeyEvent.VK_C); colorMenuItems = new JRadioButtonMenuItem[colorItems.length]; for (int i = 0; i< colorItems.length; i++){ colorMenuItems[i] = new JRadioButtonMenuItem(colorItems[i],i==0); colorMenuItems[i].addActionListener(this); colorMenuItems[i].setActionCommand("color" + i); colorMenu.add(colorMenuItems[i]); cg.add(colorMenuItems[i]); } colorMenuItems[0].setSelected(true); displayMenu.add(colorMenu); JMenuItem spacingItem = new JMenuItem("LD Display Spacing"); spacingItem.setMnemonic(KeyEvent.VK_S); spacingItem.addActionListener(this); displayMenu.add(spacingItem); displayMenu.setEnabled(false); //analysis menu analysisMenu = new JMenu("Analysis"); analysisMenu.setMnemonic(KeyEvent.VK_A); menuBar.add(analysisMenu); //a submenu ButtonGroup bg = new ButtonGroup(); JMenu blockMenu = new JMenu("Define Blocks"); blockMenu.setMnemonic(KeyEvent.VK_B); blockMenuItems = new JRadioButtonMenuItem[blockItems.length]; for (int i = 0; i < blockItems.length; i++){ blockMenuItems[i] = new JRadioButtonMenuItem(blockItems[i], i==0); blockMenuItems[i].addActionListener(this); blockMenuItems[i].setActionCommand("block" + i); blockMenuItems[i].setEnabled(false); blockMenu.add(blockMenuItems[i]); bg.add(blockMenuItems[i]); } analysisMenu.add(blockMenu); clearBlocksItem = new JMenuItem(CLEAR_BLOCKS); setAccelerator(clearBlocksItem, 'C', false); clearBlocksItem.addActionListener(this); clearBlocksItem.setEnabled(false); analysisMenu.add(clearBlocksItem); JMenuItem customizeBlocksItem = new JMenuItem(CUST_BLOCKS); customizeBlocksItem.addActionListener(this); analysisMenu.add(customizeBlocksItem); analysisMenu.setEnabled(false); //color key keyMenu = new JMenu("Key"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(keyMenu); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* Configuration.readConfigFile(); if(Configuration.isCheckForUpdate()) { Object[] options = {"Yes", "Not now", "Never ask again"}; int n = JOptionPane.showOptionDialog(this, "Would you like to check if a new version " + "of haploview is available?", "Check for update", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if(n == JOptionPane.YES_OPTION) { UpdateChecker uc = new UpdateChecker(); if(uc.checkForUpdate()) { JOptionPane.showMessageDialog(this, "A new version of Haploview is available!\n Visit http://www.broad.mit.edu/mpg/haploview/ to download the new version\n (current version: " + Constants.VERSION + " newest version: " + uc.getNewVersion() + ")" , "Update Available", JOptionPane.INFORMATION_MESSAGE); } } else if(n == JOptionPane.CANCEL_OPTION) { Configuration.setCheckForUpdate(false); Configuration.writeConfigFile(); } } */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); }
|
public HaploView(){ try{ fc = new JFileChooser(System.getProperty("user.dir")); }catch(NullPointerException n){ try{ UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); fc = new JFileChooser(System.getProperty("user.dir")); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e){ } } //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); analysisItem = new JMenuItem(READ_ANALYSIS_TRACK); setAccelerator(analysisItem, 'A', false); analysisItem.addActionListener(this); analysisItem.setEnabled(false); fileMenu.add(analysisItem); blocksItem = new JMenuItem(READ_BLOCKS_FILE); setAccelerator(blocksItem, 'B', false); blocksItem.addActionListener(this); blocksItem.setEnabled(false); fileMenu.add(blocksItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); fileMenu.setMnemonic(KeyEvent.VK_F); menuItem = new JMenuItem("Quit"); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu displayMenu = new JMenu("Display"); displayMenu.setMnemonic(KeyEvent.VK_D); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); viewMenuItems[i].setEnabled(false); group.add(viewMenuItems[i]); } displayMenu.addSeparator(); //a submenu ButtonGroup zg = new ButtonGroup(); JMenu zoomMenu = new JMenu("LD zoom"); zoomMenu.setMnemonic(KeyEvent.VK_Z); zoomMenuItems = new JRadioButtonMenuItem[zoomItems.length]; for (int i = 0; i < zoomItems.length; i++){ zoomMenuItems[i] = new JRadioButtonMenuItem(zoomItems[i], i==0); zoomMenuItems[i].addActionListener(this); zoomMenuItems[i].setActionCommand("zoom" + i); zoomMenu.add(zoomMenuItems[i]); zg.add(zoomMenuItems[i]); } displayMenu.add(zoomMenu); //another submenu ButtonGroup cg = new ButtonGroup(); JMenu colorMenu = new JMenu("LD color scheme"); colorMenu.setMnemonic(KeyEvent.VK_C); colorMenuItems = new JRadioButtonMenuItem[colorItems.length]; for (int i = 0; i< colorItems.length; i++){ colorMenuItems[i] = new JRadioButtonMenuItem(colorItems[i],i==0); colorMenuItems[i].addActionListener(this); colorMenuItems[i].setActionCommand("color" + i); colorMenu.add(colorMenuItems[i]); cg.add(colorMenuItems[i]); } colorMenuItems[Options.getLDColorScheme()].setSelected(true); displayMenu.add(colorMenu); JMenuItem spacingItem = new JMenuItem("LD Display Spacing"); spacingItem.setMnemonic(KeyEvent.VK_S); spacingItem.addActionListener(this); displayMenu.add(spacingItem); displayMenu.setEnabled(false); //analysis menu analysisMenu = new JMenu("Analysis"); analysisMenu.setMnemonic(KeyEvent.VK_A); menuBar.add(analysisMenu); //a submenu ButtonGroup bg = new ButtonGroup(); JMenu blockMenu = new JMenu("Define Blocks"); blockMenu.setMnemonic(KeyEvent.VK_B); blockMenuItems = new JRadioButtonMenuItem[blockItems.length]; for (int i = 0; i < blockItems.length; i++){ blockMenuItems[i] = new JRadioButtonMenuItem(blockItems[i], i==0); blockMenuItems[i].addActionListener(this); blockMenuItems[i].setActionCommand("block" + i); blockMenuItems[i].setEnabled(false); blockMenu.add(blockMenuItems[i]); bg.add(blockMenuItems[i]); } analysisMenu.add(blockMenu); clearBlocksItem = new JMenuItem(CLEAR_BLOCKS); setAccelerator(clearBlocksItem, 'C', false); clearBlocksItem.addActionListener(this); clearBlocksItem.setEnabled(false); analysisMenu.add(clearBlocksItem); JMenuItem customizeBlocksItem = new JMenuItem(CUST_BLOCKS); customizeBlocksItem.addActionListener(this); analysisMenu.add(customizeBlocksItem); analysisMenu.setEnabled(false); //color key keyMenu = new JMenu("Key"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(keyMenu); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* Configuration.readConfigFile(); if(Configuration.isCheckForUpdate()) { Object[] options = {"Yes", "Not now", "Never ask again"}; int n = JOptionPane.showOptionDialog(this, "Would you like to check if a new version " + "of haploview is available?", "Check for update", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if(n == JOptionPane.YES_OPTION) { UpdateChecker uc = new UpdateChecker(); if(uc.checkForUpdate()) { JOptionPane.showMessageDialog(this, "A new version of Haploview is available!\n Visit http://www.broad.mit.edu/mpg/haploview/ to download the new version\n (current version: " + Constants.VERSION + " newest version: " + uc.getNewVersion() + ")" , "Update Available", JOptionPane.INFORMATION_MESSAGE); } } else if(n == JOptionPane.CANCEL_OPTION) { Configuration.setCheckForUpdate(false); Configuration.writeConfigFile(); } } */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); }
| 1,109,670
|
public PresentationObject getLetterForm(IWContext iwc) { Table T = new Table(); TextInput fromAddress = new TextInput("from_address"); fromAddress.setLength(80); TextInput fromName = new TextInput("from_name"); fromName.setLength(80); TextInput subject = new TextInput("subject"); subject.setLength(80); TextArea body = new TextArea("body", 70, 20); int row = 1; if (topics != null && topics.size() > 0) { T.add(tf.format(iwrb.getLocalizedString("list.topic", "Topic"), tf.HEADER), 1, row); DropdownMenu drp = new DropdownMenu("topic_id"); drp.setToSubmit(); java.util.Iterator iter = topics.iterator(); EmailTopic tpc; if (topics.size() > 1) { while (iter.hasNext()) { tpc = (EmailTopic) iter.next(); if(defaultTopic == null) defaultTopic = tpc; drp.addMenuElement(tpc.toString(), tpc.getName()); } if(topic>0) drp.setSelectedElement(topic); T.add(drp, 2, row++); } else if (iter.hasNext()) { tpc = (EmailTopic) iter.next(); defaultTopic = tpc; T.add(new HiddenInput("topic_id", tpc.toString()), 2, row++); } } if(defaultTopic!=null){ fromName.setContent(defaultTopic.getSenderName()); fromAddress.setContent(defaultTopic.getSenderEmail()); if(inpSubject!=null) subject.setContent(inpSubject); body.setContent(inpBody); } T.add( tf.format(iwrb.getLocalizedString("letter.from_name", "Sender name"), tf.HEADER), 1, row); T.add(fromName, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.from_address", "Sender address"), tf.HEADER),1,row); T.add(fromAddress, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.subject", "Subject"), tf.HEADER), 1, row); T.add(subject, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.body", "Body"), tf.HEADER), 1, row); T.add(body, 2, row++); SubmitButton send = new SubmitButton(iwrb.getLocalizedImageButton("send", "Send"), "send"); //SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),"save"); //CheckBox save = new CheckBox("save", "true"); Table submitTable = new Table(5, 1); //submitTable.add(tf.format(iwrb.getLocalizedString("save_to_archive","Save to archive")),3,1); //submitTable.add(save,3,1); submitTable.add(send, 5, 1); T.add(submitTable, 2, row); T.setAlignment(2, row, "right"); return T; }
|
public PresentationObject getLetterForm(IWContext iwc) { Table T = new Table(); TextInput fromAddress = new TextInput("from_address"); fromAddress.setLength(80); TextInput fromName = new TextInput("from_name"); fromName.setLength(80); TextInput subject = new TextInput("subject"); subject.setLength(80); TextArea body = new TextArea("body", 70, 20); int row = 1; if (topics != null && topics.size() > 0) { T.add(tf.format(iwrb.getLocalizedString("list.topic", "Topic"), tf.HEADER), 1, row); DropdownMenu drp = new DropdownMenu("topic_id"); drp.setToSubmit(); java.util.Iterator iter = topics.iterator(); EmailTopic tpc; if (topics.size() > 1) { while (iter.hasNext()) { tpc = (EmailTopic) iter.next(); if(defaultTopic == null) defaultTopic = tpc; drp.addMenuElement(tpc.getIdentifier().toString(), tpc.getName()); } if(topic>0) drp.setSelectedElement(topic); T.add(drp, 2, row++); } else if (iter.hasNext()) { tpc = (EmailTopic) iter.next(); defaultTopic = tpc; T.add(new HiddenInput("topic_id", tpc.toString()), 2, row++); } } if(defaultTopic!=null){ fromName.setContent(defaultTopic.getSenderName()); fromAddress.setContent(defaultTopic.getSenderEmail()); if(inpSubject!=null) subject.setContent(inpSubject); body.setContent(inpBody); } T.add( tf.format(iwrb.getLocalizedString("letter.from_name", "Sender name"), tf.HEADER), 1, row); T.add(fromName, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.from_address", "Sender address"), tf.HEADER),1,row); T.add(fromAddress, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.subject", "Subject"), tf.HEADER), 1, row); T.add(subject, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.body", "Body"), tf.HEADER), 1, row); T.add(body, 2, row++); SubmitButton send = new SubmitButton(iwrb.getLocalizedImageButton("send", "Send"), "send"); //SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),"save"); //CheckBox save = new CheckBox("save", "true"); Table submitTable = new Table(5, 1); //submitTable.add(tf.format(iwrb.getLocalizedString("save_to_archive","Save to archive")),3,1); //submitTable.add(save,3,1); submitTable.add(send, 5, 1); T.add(submitTable, 2, row); T.setAlignment(2, row, "right"); return T; }
| 1,109,671
|
public PresentationObject getLetterForm(IWContext iwc) { Table T = new Table(); TextInput fromAddress = new TextInput("from_address"); fromAddress.setLength(80); TextInput fromName = new TextInput("from_name"); fromName.setLength(80); TextInput subject = new TextInput("subject"); subject.setLength(80); TextArea body = new TextArea("body", 70, 20); int row = 1; if (topics != null && topics.size() > 0) { T.add(tf.format(iwrb.getLocalizedString("list.topic", "Topic"), tf.HEADER), 1, row); DropdownMenu drp = new DropdownMenu("topic_id"); drp.setToSubmit(); java.util.Iterator iter = topics.iterator(); EmailTopic tpc; if (topics.size() > 1) { while (iter.hasNext()) { tpc = (EmailTopic) iter.next(); if(defaultTopic == null) defaultTopic = tpc; drp.addMenuElement(tpc.toString(), tpc.getName()); } if(topic>0) drp.setSelectedElement(topic); T.add(drp, 2, row++); } else if (iter.hasNext()) { tpc = (EmailTopic) iter.next(); defaultTopic = tpc; T.add(new HiddenInput("topic_id", tpc.toString()), 2, row++); } } if(defaultTopic!=null){ fromName.setContent(defaultTopic.getSenderName()); fromAddress.setContent(defaultTopic.getSenderEmail()); if(inpSubject!=null) subject.setContent(inpSubject); body.setContent(inpBody); } T.add( tf.format(iwrb.getLocalizedString("letter.from_name", "Sender name"), tf.HEADER), 1, row); T.add(fromName, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.from_address", "Sender address"), tf.HEADER),1,row); T.add(fromAddress, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.subject", "Subject"), tf.HEADER), 1, row); T.add(subject, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.body", "Body"), tf.HEADER), 1, row); T.add(body, 2, row++); SubmitButton send = new SubmitButton(iwrb.getLocalizedImageButton("send", "Send"), "send"); //SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),"save"); //CheckBox save = new CheckBox("save", "true"); Table submitTable = new Table(5, 1); //submitTable.add(tf.format(iwrb.getLocalizedString("save_to_archive","Save to archive")),3,1); //submitTable.add(save,3,1); submitTable.add(send, 5, 1); T.add(submitTable, 2, row); T.setAlignment(2, row, "right"); return T; }
|
public PresentationObject getLetterForm(IWContext iwc) { Table T = new Table(); TextInput fromAddress = new TextInput("from_address"); fromAddress.setLength(80); TextInput fromName = new TextInput("from_name"); fromName.setLength(80); TextInput subject = new TextInput("subject"); subject.setLength(80); TextArea body = new TextArea("body", 70, 20); int row = 1; if (topics != null && topics.size() > 0) { T.add(tf.format(iwrb.getLocalizedString("list.topic", "Topic"), tf.HEADER), 1, row); DropdownMenu drp = new DropdownMenu("topic_id"); drp.setToSubmit(); java.util.Iterator iter = topics.iterator(); EmailTopic tpc; if (topics.size() > 1) { while (iter.hasNext()) { tpc = (EmailTopic) iter.next(); if(defaultTopic == null) defaultTopic = tpc; drp.addMenuElement(tpc.toString(), tpc.getName()); } if(topic>0) drp.setSelectedElement(topic); T.add(drp, 2, row++); } else if (iter.hasNext()) { tpc = (EmailTopic) iter.next(); defaultTopic = tpc; T.add(new HiddenInput("topic_id",tpc.getIdentifier().toString()), 2, row++); } } if(defaultTopic!=null){ fromName.setContent(defaultTopic.getSenderName()); fromAddress.setContent(defaultTopic.getSenderEmail()); if(inpSubject!=null) subject.setContent(inpSubject); body.setContent(inpBody); } T.add( tf.format(iwrb.getLocalizedString("letter.from_name", "Sender name"), tf.HEADER), 1, row); T.add(fromName, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.from_address", "Sender address"), tf.HEADER),1,row); T.add(fromAddress, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.subject", "Subject"), tf.HEADER), 1, row); T.add(subject, 2, row++); T.add(tf.format(iwrb.getLocalizedString("letter.body", "Body"), tf.HEADER), 1, row); T.add(body, 2, row++); SubmitButton send = new SubmitButton(iwrb.getLocalizedImageButton("send", "Send"), "send"); //SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),"save"); //CheckBox save = new CheckBox("save", "true"); Table submitTable = new Table(5, 1); //submitTable.add(tf.format(iwrb.getLocalizedString("save_to_archive","Save to archive")),3,1); //submitTable.add(save,3,1); submitTable.add(send, 5, 1); T.add(submitTable, 2, row); T.setAlignment(2, row, "right"); return T; }
| 1,109,672
|
public void doTag(XMLOutput output) throws Exception { if (test != null) { while (test.evaluateAsBoolean(getContext())) { if (log.isDebugEnabled()) { log.debug("evaluated to true! gonna keep on chuggin!"); } invokeBody(output); } } else { throw new MissingAttributeException("test"); } }
|
public void doTag(XMLOutput output) throws MissingAttributeException, Exception { if (test != null) { while (test.evaluateAsBoolean(getContext())) { if (log.isDebugEnabled()) { log.debug("evaluated to true! gonna keep on chuggin!"); } invokeBody(output); } } else { throw new MissingAttributeException("test"); } }
| 1,109,673
|
void processData(){ final long maxCompDist = Long.parseLong(filenames[2])*1000; try{ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final SwingWorker worker = new SwingWorker(){ public Object construct(){ dPrimeDisplay=null; infoKnown = false; if (!(filenames[1].equals(""))){ readMarkers(new File(filenames[1])); } theData.generateDPrimeTable(maxCompDist); theData.guessBlocks(0); drawPicture(theData); theData.finished = true; return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (theData.finished){ timer.stop(); defineBlocksItem.setEnabled(true); readMarkerItem.setEnabled(true); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }); worker.start(); timer.start(); }catch (RuntimeException rtexec){ JOptionPane.showMessageDialog(this, "An error has occured. It is probably related to file format:\n"+rtexec.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
void processData(){ maxCompDist = Long.parseLong(filenames[2])*1000; try{ this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final SwingWorker worker = new SwingWorker(){ public Object construct(){ dPrimeDisplay=null; infoKnown = false; if (!(filenames[1].equals(""))){ readMarkers(new File(filenames[1])); } theData.generateDPrimeTable(maxCompDist); theData.guessBlocks(0); drawPicture(theData); theData.finished = true; return ""; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (theData.finished){ timer.stop(); defineBlocksItem.setEnabled(true); readMarkerItem.setEnabled(true); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }); worker.start(); timer.start(); }catch (RuntimeException rtexec){ JOptionPane.showMessageDialog(this, "An error has occured. It is probably related to file format:\n"+rtexec.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
| 1,109,674
|
void readMarkers(File inputFile){ try { int good = theData.prepareMarkerInput(inputFile); if (good == -1){ JOptionPane.showMessageDialog(this, "Number of markers in info file does not match number of markers in dataset.", "Error", JOptionPane.ERROR_MESSAGE); }else{ infoKnown=true; if (dPrimeDisplay != null){ dPrimeDisplay.loadMarkers(); } } }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (RuntimeException rtexec){ JOptionPane.showMessageDialog(this, "An error has occured. It is probably related to file format:\n"+rtexec.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
void readMarkers(File inputFile){ try { int good = theData.prepareMarkerInput(inputFile,maxCompDist); if (good == -1){ JOptionPane.showMessageDialog(this, "Number of markers in info file does not match number of markers in dataset.", "Error", JOptionPane.ERROR_MESSAGE); }else{ infoKnown=true; if (dPrimeDisplay != null){ dPrimeDisplay.loadMarkers(); } } }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); }catch (RuntimeException rtexec){ JOptionPane.showMessageDialog(this, "An error has occured. It is probably related to file format:\n"+rtexec.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
| 1,109,675
|
public void checkColumnLocked(SQLColumn col) throws LockedColumnException { for (SQLRelationship.ColumnMapping cm : getMappings()) { if (cm.getFkColumn() == col) { throw new LockedColumnException(this); } } }
|
public void checkColumnLocked(SQLColumn col) throws LockedColumnException { for (SQLRelationship.ColumnMapping cm : getMappings()) { if (cm.getFkColumn() == col) { throw new LockedColumnException(this,col); } } }
| 1,109,676
|
public void testParse() throws Exception { InputStream in = getClass().getResourceAsStream( "example.jelly" ); XMLParser parser = new XMLParser(); Script script = parser.parse( in ); script = script.compile(); log.debug( "Found: " + script ); assertTrue( "Script is a TagScript", script instanceof TagScript ); Context context = new Context(); StringWriter buffer = new StringWriter(); script.run( context, XMLOutput.createXMLOutput( buffer ) ); String text = buffer.toString().trim(); if ( log.isDebugEnabled() ) { log.debug( "Evaluated script as..." ); log.debug( text ); } assertEquals( "Produces the correct output", "It works!", text ); }
|
public void testParse() throws Exception { InputStream in = getClass().getResourceAsStream( "example.jelly" ); XMLParser parser = new XMLParser(); Script script = parser.parse( in ); script = script.compile(); log.debug( "Found: " + script ); assertTrue( "Script is a TagScript", script instanceof TagScript ); JellyContext context = new JellyContext(); StringWriter buffer = new StringWriter(); script.run( context, XMLOutput.createXMLOutput( buffer ) ); String text = buffer.toString().trim(); if ( log.isDebugEnabled() ) { log.debug( "Evaluated script as..." ); log.debug( text ); } assertEquals( "Produces the correct output", "It works!", text ); }
| 1,109,678
|
public void setDataType(Object dataType) { this.dataType = dataType; setDynaBean( new WrapDynaBean(dataType) ); }
|
public void setDataType(Object dataType) { this.dataType = dataType; setDynaBean( new ConvertingWrapDynaBean(dataType) ); }
| 1,109,679
|
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); 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); } }
|
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{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black);else{ showWM = false; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); if (size.height < pref.height){ setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); else { g2.translate((size.width - pref.width) / 2, 0); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black);else{ cumulativeGap[i] = cumulativeGap[i-1]; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); */ //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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); highX = ((visRect.x + visRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); lowY = ((visRect.x-clickXShift)+(visRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); highY = (((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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(); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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]; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); if (values[x] > max){ max = values[x]; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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)))); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); top += TRACK_HEIGHT + TRACK_GAP; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black);else{ g2.setFont(markerNameFont); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); g2.drawString(Chromosome.getFilteredMarker(x).getName(),TEXT_GAP, x*boxSize + ascent/3); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); top += boxRadius/2; // give a little space between numbers and boxes }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //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{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); // 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); for (int y = lowY; y < highY; y++) { if (dPrimeTable[x][y] == null){ continue; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black);else{ g2.setStroke(dashedFatStroke); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); g2.drawLine(left+j*boxSize-boxSize/2, top-blockDispHeight, left+j*boxSize+boxSize/2, top-blockDispHeight); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //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)"; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); g2.drawString(labelString, left+first*boxSize-boxSize/2+TEXT_GAP, top-boxSize/3); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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]); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); gp.closePath(); gw2.setColor(dPrimeTable[x][y].getColor()); gw2.fill(gp); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); noImage = false; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //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{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black);else{ voffset = WM_BD_HEIGHT/2; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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; }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); 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)); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //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); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //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); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black);
| 1,109,680
|
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); 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); } }
|
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); 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); } }
| 1,109,681
|
public void tallyCCInd(byte a1, byte a2, int cc){ //case = 0, control = 1 for int cc if (a1 == 5 && a2 == 5){ counts[cc][0]++; counts[cc][1]++; }else{ //seed the alleles as soon as they're found if (allele1 == 0){ allele1 = a1; } if (a1 != 0){ if (a1 == allele1){ counts[cc][0] ++; }else{ counts[cc][1] ++; } } if (a2 != 0){ if (a2 == allele1){ counts[cc][0]++; }else{ counts[cc][1]++; } } } }
|
public void tallyCCInd(byte a1, byte a2, int cc){ //case = 0, control = 1 for int cc if (a1 >= 5 && a2 >= 5){ counts[cc][0]++; counts[cc][1]++; }else{ //seed the alleles as soon as they're found if (allele1 == 0){ allele1 = a1; } if (a1 != 0){ if (a1 == allele1){ counts[cc][0] ++; }else{ counts[cc][1] ++; } } if (a2 != 0){ if (a2 == allele1){ counts[cc][0]++; }else{ counts[cc][1]++; } } } }
| 1,109,682
|
public void tallyTrioInd(byte alleleT, byte alleleU) { if(alleleT == 5 && alleleU == 5) { if(tallyHet){ counts[0][0]++; counts[1][1]++; counts[0][1]++; counts[1][0]++; this.tallyHet = false; } else { this.tallyHet = true; } } else if( (alleleT != alleleU) && (alleleT!=0) && (alleleU!=0) ) { if(allele1==0 && allele2==0 ) { allele1 = alleleT; allele2 = alleleU; } if(alleleT == allele1) { counts[0][0]++; } else if(alleleT==allele2) { counts[0][1]++; } if(alleleU == allele1){ counts[1][0]++; } else if(alleleU == allele2) { counts[1][1]++; } } //System.out.println( counts[0][0] + "\t" + counts[1][1] + "\t" + counts[0][1] + "\t" + counts[1][0]); }
|
public void tallyTrioInd(byte alleleT, byte alleleU) { if(alleleT >= 5 && alleleU >= 5) { if(tallyHet){ counts[0][0]++; counts[1][1]++; counts[0][1]++; counts[1][0]++; this.tallyHet = false; } else { this.tallyHet = true; } } else if( (alleleT != alleleU) && (alleleT!=0) && (alleleU!=0) ) { if(allele1==0 && allele2==0 ) { allele1 = alleleT; allele2 = alleleU; } if(alleleT == allele1) { counts[0][0]++; } else if(alleleT==allele2) { counts[0][1]++; } if(alleleU == allele1){ counts[1][0]++; } else if(alleleU == allele2) { counts[1][1]++; } } //System.out.println( counts[0][0] + "\t" + counts[1][1] + "\t" + counts[0][1] + "\t" + counts[1][0]); }
| 1,109,683
|
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; entries != null && 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); } }
|
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; entries != null && i < entries.length; i++) {// TODO do we need to check the state? assertEquals(1, pop3Client.getState()); POP3MessageInfo entry = entries[i]; 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); } }
| 1,109,684
|
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; entries != null && 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); } }
|
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; entries != null && 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); } }
| 1,109,685
|
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; entries != null && 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); } }
|
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; entries != null && 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); } }
| 1,109,686
|
public Expression createExpression(final String text) throws Exception {/* org.apache.commons.jexl.Expression expr = org.apache.commons.jexl.ExpressionFactory.createExpression(text); if ( isSupportAntVariables() ) { expr.addPostResolver(new FlatResolver()); } return new JexlExpression( expr );*/ final Expression jexlExpression = new JexlExpression( org.apache.commons.jexl.ExpressionFactory.createExpression(text) ); if ( isSupportAntVariables() && isValidAntVariableName(text) ) { ExpressionSupport expr = new ExpressionSupport() { public Object evaluate(JellyContext context) { Object answer = jexlExpression.evaluate(context); if ( answer == null ) { answer = context.getVariable(text); } return answer; } public String getExpressionText() { return text; } public String toString() { return super.toString() + "[expression:" + text + "]"; } }; return expr; } return jexlExpression; }
|
public Expression createExpression(final String text) throws Exception {/* org.apache.commons.jexl.Expression expr = org.apache.commons.jexl.ExpressionFactory.createExpression(text); if ( isSupportAntVariables() ) { expr.addPostResolver(new FlatResolver()); } return new JexlExpression( expr );*/ final Expression jexlExpression = new JexlExpression( org.apache.commons.jexl.ExpressionFactory.createExpression(text) ); if ( isSupportAntVariables() && isValidAntVariableName(text) ) { ExpressionSupport expr = new ExpressionSupport() { public Object evaluate(JellyContext context) { Object answer = jexlExpression.evaluate(context); if ( answer == null ) { answer = context.getVariable(text); } return answer; } public String getExpressionText() { return "${" + text + "}"; } public String toString() { return super.toString() + "[expression:" + text + "]"; } }; return expr; } return jexlExpression; }
| 1,109,687
|
public String getExpressionText() { return text; }
|
public String getExpressionText() { return "${" + text + "}"; }
| 1,109,688
|
public void doTag(final XMLOutput output) throws Exception { if ( this.var == null ) { throw new MissingAttributeException( "var" ); } if ( this.delim == null ) { throw new MissingAttributeException( "var" ); } StringTokenizer tokenizer = new StringTokenizer( getBodyText(), this.delim ); List tokens = new ArrayList(); while ( tokenizer.hasMoreTokens() ) { tokens.add( tokenizer.nextToken() ); } getContext().setVariable( this.var, tokens ); }
|
public void doTag(final XMLOutput output) throws Exception { if ( this.var == null ) { throw new MissingAttributeException( "delim" ); } if ( this.delim == null ) { throw new MissingAttributeException( "delim" ); } StringTokenizer tokenizer = new StringTokenizer( getBodyText(), this.delim ); List tokens = new ArrayList(); while ( tokenizer.hasMoreTokens() ) { tokens.add( tokenizer.nextToken() ); } getContext().setVariable( this.var, tokens ); }
| 1,109,689
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.