bugged
stringlengths
6
599k
fixed
stringlengths
10
599k
__index_level_0__
int64
0
1.13M
protected void configure() { // load the properties file of libraries available InputStream in = null; URL url = getClassLoader().getResource("org/apache/commons/jelly/jelly.properties"); if (url != null) { log.debug("Loading Jelly default tag libraries from: " + url); Properties properties = new Properties(); try { in = url.openStream(); properties.load(in); for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String uri = (String) entry.getKey(); String className = (String) entry.getValue(); context.registerTagLibrary("jelly:" + uri, className); } } catch (IOException e) { log.error("Could not load jelly properties from: " + url + ". Reason: " + e, e); } finally { try { in.close(); } catch (Exception e) { // ignore } } } }
protected void configure() { // load the properties file of libraries available InputStream in = null; URL url = getClassLoader().getResource("org/apache/commons/jelly/jelly.properties"); if (url != null) { log.debug("Loading Jelly default tag libraries from: " + url); Properties properties = new Properties(); try { in = url.openStream(); properties.load(in); for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String uri = (String) entry.getKey(); String className = (String) entry.getValue(); context.registerTagLibrary("jelly:" + uri, className); } } catch (IOException e) { log.error("Could not load jelly properties from: " + url + ". Reason: " + e, e); } finally { try { in.close(); } catch (Exception e) { // ignore } } } }
1,109,690
public String getElementName();
String getElementName();
1,109,691
public void setColumnNumber(int columnNumber);
void setColumnNumber(int columnNumber);
1,109,692
public void setElementName(String elementName);
void setElementName(String elementName);
1,109,693
public void setFileName(String fileName);
void setFileName(String fileName);
1,109,694
public void setLineNumber(int lineNumber);
void setLineNumber(int lineNumber);
1,109,695
public String getMessage() { return super.getMessage() + " At line: " + lineNumber + " column: " + columnNumber; }
public String getMessage() { return super.getMessage() + " File: " + fileName + " At tag <" + elementName + ">: line: " + lineNumber + " column: " + columnNumber; }
1,109,696
private void argHandler(String[] args){ argHandlerMessages = new Vector(); int maxDistance = -1; //this means that user didn't specify any output type if it doesn't get changed below blockOutputType = -1; double hapThresh = -1; double minimumMAF=-1; double spacingThresh = -1; double minimumGenoPercent = -1; double hwCutoff = -1; double missingCutoff = -1; int maxMendel = -1; boolean assocTDT = false; boolean assocCC = false; permutationCount = 0; tagging = Tagger.NONE; maxNumTags = Tagger.DEFAULT_MAXNUMTAGS; findTags = true; double cutHighCI = -1; double cutLowCI = -1; double mafThresh = -1; double recHighCI = -1; double informFrac = -1; double fourGameteCutoff = -1; double spineDP = -1; for(int i =0; i < args.length; i++) { if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) { System.out.println(HELP_OUTPUT); System.exit(0); } else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) { nogui = true; } else if(args[i].equalsIgnoreCase("-log")){ i++; if (i >= args.length || args[i].charAt(0) == '-'){ logName = "haploview.log"; i--; }else{ logName = args[i]; } } else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) { i++; if( i>=args.length || (args[i].charAt(0) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(pedFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used"); } pedFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-pcloadletter")){ die("PC LOADLETTER?! What the fuck does that mean?!"); } else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){ skipCheck = true; } else if (args[i].equalsIgnoreCase("-excludeMarkers")){ i++; if(i>=args.length || (args[i].charAt(0) == '-')){ die("-excludeMarkers requires a list of markers"); } else { StringTokenizer str = new StringTokenizer(args[i],","); try { StringBuffer sb = new StringBuffer(); if (!quietMode) sb.append("Excluding markers: "); while(str.hasMoreTokens()) { String token = str.nextToken(); if(token.indexOf("..") != -1) { int lastIndex = token.indexOf(".."); int rangeStart = Integer.parseInt(token.substring(0,lastIndex)); int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length())); for(int j=rangeStart;j<=rangeEnd;j++) { if (!quietMode) sb.append(j+" "); excludedMarkers.add(new Integer(j)); } } else { if (!quietMode) sb.append(token+" "); excludedMarkers.add(new Integer(token)); } } argHandlerMessages.add(sb.toString()); } catch(NumberFormatException nfe) { die("-excludeMarkers argument should be of the format: 1,3,5..8,12"); } } } else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-haps")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapsFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used"); } hapsFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(infoFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used"); } infoFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapmapFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used"); } hapmapFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpdata")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpdataFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap data file listed will be used"); } phasedhmpdataFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpsample")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpsampleFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap sample file listed will be used"); } phasedhmpsampleFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmplegend")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmplegendFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap legend file listed will be used"); } phasedhmplegendFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhapmapdl")){ phasedhapmapDownload = true; } else if (args[i].equalsIgnoreCase("-plink")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last PLINK file listed will be used"); } plinkFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-map")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last map file listed will be used"); } mapFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ blockFileName = args[i]; blockOutputType = BLOX_CUSTOM; }else{ die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-png")){ outputPNG = true; } else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){ outputCompressedPNG = true; } else if (args[i].equalsIgnoreCase("-track")){ i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ trackFileName = args[i]; }else{ die("-track requires a filename"); } } else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(blockOutputType != -1){ die("Only one block output type argument is allowed."); } if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){ blockOutputType = BLOX_GABRIEL; } else if(args[i].equalsIgnoreCase("GAM")){ blockOutputType = BLOX_4GAM; } else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){ blockOutputType = BLOX_SPINE; } else if(args[i].equalsIgnoreCase("ALL")) { blockOutputType = BLOX_ALL; } } else { //defaults to SFS output blockOutputType = BLOX_GABRIEL; i--; } } else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) { outputDprime = true; } else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){ outputCheck = true; } else if (args[i].equalsIgnoreCase("-indcheck")){ individualCheck = true; } else if (args[i].equalsIgnoreCase("-mendel")){ mendel = true; } else if (args[i].equalsIgnoreCase("-malehets")){ malehets = true; } else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) { i++; maxDistance = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) { //batch mode i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(batchFileName != null){ argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used"); } batchFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-hapthresh")) { i++; hapThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-spacing")) { i++; spacingThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-minMAF")) { i++; minimumMAF = getDoubleArg(args,i,0,0.5); } else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) { i++; minimumGenoPercent = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-hwcutoff")) { i++; hwCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-maxMendel") ) { i++; maxMendel = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-missingcutoff")) { i++; missingCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-assoctdt")) { assocTDT = true; } else if(args[i].equalsIgnoreCase("-assoccc")) { assocCC = true; } else if(args[i].equalsIgnoreCase("-randomcc")){ assocCC = true; randomizeAffection = true; } else if(args[i].equalsIgnoreCase("-ldcolorscheme")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(args[i].equalsIgnoreCase("default")){ Options.setLDColorScheme(STD_SCHEME); } else if(args[i].equalsIgnoreCase("RSQ")){ Options.setLDColorScheme(RSQ_SCHEME); } else if(args[i].equalsIgnoreCase("DPALT") ){ Options.setLDColorScheme(WMF_SCHEME); } else if(args[i].equalsIgnoreCase("GAB")) { Options.setLDColorScheme(GAB_SCHEME); } else if(args[i].equalsIgnoreCase("GAM")) { Options.setLDColorScheme(GAM_SCHEME); } else if(args[i].equalsIgnoreCase("GOLD")) { Options.setLDColorScheme(GOLD_SCHEME); } } else { //defaults to STD color scheme Options.setLDColorScheme(STD_SCHEME); i--; } } else if(args[i].equalsIgnoreCase("-blockCutHighCI")) { i++; cutHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockCutLowCI")) { i++; cutLowCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockMafThresh")) { i++; mafThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockRecHighCI")) { i++; recHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockInformFrac")) { i++; informFrac = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-block4GamCut")) { i++; fourGameteCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockSpineDP")) { i++; spineDP = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-permtests")) { i++; doPermutationTest = true; permutationCount = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-customassoc")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ customAssocTestsFileName = args[i]; }else{ die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-aggressiveTagging")) { tagging = Tagger.AGGRESSIVE_TRIPLE; } else if (args[i].equalsIgnoreCase("-pairwiseTagging")){ tagging = Tagger.PAIRWISE_ONLY; } else if (args[i].equalsIgnoreCase("-printalltags")){ Options.setPrintAllTags(true); } else if(args[i].equalsIgnoreCase("-maxNumTags")){ i++; maxNumTags = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) { i++; tagRSquaredCutOff = getDoubleArg(args,i,0,1); } else if (args[i].equalsIgnoreCase("-dontaddtags")){ findTags = false; } else if(args[i].equalsIgnoreCase("-tagLODCutoff")) { i++; Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000)); } else if(args[i].equalsIgnoreCase("-includeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die(args[i-1] + " requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceIncludeTags = new Vector(); while(str.hasMoreTokens()) { forceIncludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-includeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceIncludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-excludeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die("-excludeTags requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceExcludeTags = new Vector(); while(str.hasMoreTokens()) { forceExcludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-excludeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceExcludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-captureAlleles")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { captureAllelesFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-designScores")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { designScoresFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-mintagdistance")){ i++; minTagDistance = args[i]; } else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { chromosomeArg =args[i]; }else { die(args[i-1] + " requires a chromosome name"); } if(!(chromosomeArg.equalsIgnoreCase("X")) && !(chromosomeArg.equalsIgnoreCase("Y"))){ try{ if (Integer.parseInt(chromosomeArg) > 22){ die("-chromosome requires a chromsome name of 1-22, X, or Y"); } }catch(NumberFormatException nfe){ die("-chromosome requires a chromsome name of 1-22, X, or Y"); } } } else if(args[i].equalsIgnoreCase("-population")){ i++; if(!(i>=args.length) && !(args[i].charAt(0)== '-')) { populationArg = args[i]; }else { die(args[i-1] + "requires a population name"); } } else if(args[i].equalsIgnoreCase("-startpos")){ i++; startPos = args[i]; } else if(args[i].equalsIgnoreCase("-endPos")){ i++; endPos = args[i]; } else if(args[i].equalsIgnoreCase("-release")){ i++; release = args[i]; } else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) { quietMode = true; } else if(args[i].equalsIgnoreCase("-gzip")){ Options.setGzip(true); } else { die("invalid parameter specified: " + args[i]); } } if (logName != null){ logString = "*****************************************************\n" + TITLE_STRING + "\tJava Version: " + JAVA_VERSION + "\n*****************************************************\n\n\n" + "Arguments:\t"; for (int i = 0; i < args.length; i++){ logString = logString + args[i] + "\t"; } logString = logString + "\n\n"; } int countOptions = 0; if(pedFileName != null) { countOptions++; } if(hapsFileName != null) { countOptions++; } if(hapmapFileName != null) { countOptions++; } if(phasedhmpdataFileName != null) { countOptions++; if(phasedhmpsampleFileName == null){ die("You must specify a sample file for phased hapmap input."); }else if(phasedhmplegendFileName == null){ die("You must specify a legend file for phased hapmap input."); } } if(phasedhapmapDownload) { countOptions++; } if(plinkFileName != null){ countOptions++; if(mapFileName == null){ die("You must specify a map file for plink format input."); } } if(batchFileName != null) { countOptions++; } if(countOptions > 1) { die("Only one genotype input file may be specified on the command line."); } else if(countOptions == 0 && nogui) { die("You must specify a genotype input file."); } //mess with vars, set defaults, etc if(skipCheck) { argHandlerMessages.add("Skipping genotype file check"); } if(maxDistance == -1){ maxDistance = MAXDIST_DEFAULT; }else{ argHandlerMessages.add("Max LD comparison distance = " +maxDistance + "kb"); } Options.setMaxDistance(maxDistance); if(hapThresh != -1) { Options.setHaplotypeDisplayThreshold(hapThresh); argHandlerMessages.add("Haplotype display threshold = " + hapThresh); } if(minimumMAF != -1) { CheckData.mafCut = minimumMAF; argHandlerMessages.add("Minimum MAF = " + minimumMAF); } if(minimumGenoPercent != -1) { CheckData.failedGenoCut = (int)(minimumGenoPercent*100); argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent); } if(hwCutoff != -1) { CheckData.hwCut = hwCutoff; argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff); } if(maxMendel != -1) { CheckData.numMendErrCut = maxMendel; argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel); } if(spacingThresh != -1) { Options.setSpacingThreshold(spacingThresh); argHandlerMessages.add("LD display spacing value = "+spacingThresh); } if(missingCutoff != -1) { Options.setMissingThreshold(missingCutoff); argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff); } if(cutHighCI != -1) { FindBlocks.cutHighCI = cutHighCI; } if(cutLowCI != -1) { FindBlocks.cutLowCI = cutLowCI; } if(mafThresh != -1) { FindBlocks.mafThresh = mafThresh; } if(recHighCI != -1) { FindBlocks.recHighCI = recHighCI; } if(informFrac != -1) { FindBlocks.informFrac = informFrac; } if(fourGameteCutoff != -1) { FindBlocks.fourGameteCutoff = fourGameteCutoff; } if(spineDP != -1) { FindBlocks.spineDP = spineDP; } if(assocTDT) { Options.setAssocTest(ASSOC_TRIO); }else if(assocCC) { Options.setAssocTest(ASSOC_CC); } if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) { die("A marker info file must be specified when performing association tests."); } if(doPermutationTest) { if(!assocCC && !assocTDT) { die("An association test type must be specified for permutation tests to be performed."); } } if(customAssocTestsFileName != null) { if(!assocCC && !assocTDT) { die("An association test type must be specified when using a custom association test file."); } if(infoFileName == null) { die("A marker info file must be specified when using a custom association test file."); } } if(tagging != Tagger.NONE) { if(infoFileName == null && hapmapFileName == null && batchFileName == null && phasedhmpdataFileName == null && !phasedhapmapDownload) { die("A marker info file must be specified when tagging."); } if(forceExcludeTags == null) { forceExcludeTags = new Vector(); } else if (forceExcludeFileName != null) { die("-excludeTags and -excludeTagsFile cannot both be used"); } if(forceExcludeFileName != null) { File excludeFile = new File(forceExcludeFileName); forceExcludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(excludeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceExcludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -excludeTagsFile."); } } if(forceIncludeTags == null ) { forceIncludeTags = new Vector(); } else if (forceIncludeFileName != null) { die("-includeTags and -includeTagsFile cannot both be used"); } if(forceIncludeFileName != null) { File includeFile = new File(forceIncludeFileName); forceIncludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(includeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceIncludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -includeTagsFile."); } } if (captureAllelesFileName != null) { File captureFile = new File(captureAllelesFileName); captureAlleleTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(captureFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ line = line.trim(); captureAlleleTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (designScoresFileName != null) { File designFile = new File(designScoresFileName); designScores = new Hashtable(1,1); try { BufferedReader br = new BufferedReader(new FileReader(designFile)); String line; int lines = 0; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ StringTokenizer st = new StringTokenizer(line); int length = st.countTokens(); if (length != 2){ die("Invalid formatting on line " + lines); } String marker = st.nextToken(); Double score = new Double(st.nextToken()); designScores.put(marker,score); } lines++; } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (minTagDistance != null) { try{ if (Integer.parseInt(minTagDistance) < 0){ die("minimum tag distance cannot be negative"); } }catch(NumberFormatException nfe){ die("minimum tag distance must be a positive integer"); } Options.setTaggerMinDistance(Integer.parseInt(minTagDistance)); } //check that there isn't any overlap between include/exclude lists Vector tempInclude = (Vector) forceIncludeTags.clone(); tempInclude.retainAll(forceExcludeTags); if(tempInclude.size() > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < tempInclude.size(); i++) { String s = (String) tempInclude.elementAt(i); sb.append(s).append(","); } die("The following markers appear in both the include and exclude lists: " + sb.toString()); } if(tagRSquaredCutOff != -1) { Options.setTaggerRsqCutoff(tagRSquaredCutOff); } } else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) { die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without a tagging option"); } if(chromosomeArg != null && hapmapFileName != null) { argHandlerMessages.add("-chromosome flag ignored when loading hapmap file"); chromosomeArg = null; } if(chromosomeArg != null) { Chromosome.setDataChrom("chr" + chromosomeArg); }else{ chromosomeArg = ""; } if (phasedhapmapDownload){ if (chromosomeArg == null){ die("-phasedhapmapdl requires a chromosome specification"); }else if (!(populationArg.equalsIgnoreCase("CEU") || populationArg.equalsIgnoreCase("YRI") || populationArg.equalsIgnoreCase("CHB+JPT"))){ die("-phasedhapmapdl requires a population specification of CEU, YRI, or CHB+JPT"); } if (Integer.parseInt(chromosomeArg) < 1 && Integer.parseInt(chromosomeArg) > 22){ if (!(chromosomeArg.equalsIgnoreCase("X")) && !(chromosomeArg.equalsIgnoreCase("Y"))){ die("-chromosome must be betweeen 1 and 22, X, or Y"); } } try{ if (Integer.parseInt(startPos) > Integer.parseInt(endPos)){ die("-endpos must be greater then -startpos"); } }catch(NumberFormatException nfe){ die("-startpos and -endpos must be integer values"); } if (release == null){ release = "21"; } if (!(release.equals("21")) && !(release.startsWith("16"))){ die("release must be either 16a or 21"); } } }
private void argHandler(String[] args){ argHandlerMessages = new Vector(); int maxDistance = -1; //this means that user didn't specify any output type if it doesn't get changed below blockOutputType = -1; double hapThresh = -1; double minimumMAF=-1; double spacingThresh = -1; double minimumGenoPercent = -1; double hwCutoff = -1; double missingCutoff = -1; int maxMendel = -1; boolean assocTDT = false; boolean assocCC = false; permutationCount = 0; tagging = Tagger.NONE; maxNumTags = Tagger.DEFAULT_MAXNUMTAGS; findTags = true; double cutHighCI = -1; double cutLowCI = -1; double mafThresh = -1; double recHighCI = -1; double informFrac = -1; double fourGameteCutoff = -1; double spineDP = -1; for(int i =0; i < args.length; i++) { if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) { System.out.println(HELP_OUTPUT); System.exit(0); } else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) { nogui = true; } else if(args[i].equalsIgnoreCase("-log")){ i++; if (i >= args.length || args[i].charAt(0) == '-'){ logName = "haploview.log"; i--; }else{ logName = args[i]; } } else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) { i++; if( i>=args.length || (args[i].charAt(0) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(pedFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used"); } pedFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-pcloadletter")){ die("PC LOADLETTER?! What the fuck does that mean?!"); } else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){ skipCheck = true; } else if (args[i].equalsIgnoreCase("-excludeMarkers")){ i++; if(i>=args.length || (args[i].charAt(0) == '-')){ die("-excludeMarkers requires a list of markers"); } else { StringTokenizer str = new StringTokenizer(args[i],","); try { StringBuffer sb = new StringBuffer(); if (!quietMode) sb.append("Excluding markers: "); while(str.hasMoreTokens()) { String token = str.nextToken(); if(token.indexOf("..") != -1) { int lastIndex = token.indexOf(".."); int rangeStart = Integer.parseInt(token.substring(0,lastIndex)); int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length())); for(int j=rangeStart;j<=rangeEnd;j++) { if (!quietMode) sb.append(j+" "); excludedMarkers.add(new Integer(j)); } } else { if (!quietMode) sb.append(token+" "); excludedMarkers.add(new Integer(token)); } } argHandlerMessages.add(sb.toString()); } catch(NumberFormatException nfe) { die("-excludeMarkers argument should be of the format: 1,3,5..8,12"); } } } else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-haps")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapsFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used"); } hapsFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(infoFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used"); } infoFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapmapFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used"); } hapmapFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpdata")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpdataFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap data file listed will be used"); } phasedhmpdataFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpsample")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpsampleFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap sample file listed will be used"); } phasedhmpsampleFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmplegend")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmplegendFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap legend file listed will be used"); } phasedhmplegendFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhapmapdl")){ phasedhapmapDownload = true; } else if (args[i].equalsIgnoreCase("-plink")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last PLINK file listed will be used"); } plinkFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-map")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last map file listed will be used"); } mapFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ blockFileName = args[i]; blockOutputType = BLOX_CUSTOM; }else{ die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-png")){ outputPNG = true; } else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){ outputCompressedPNG = true; } else if (args[i].equalsIgnoreCase("-track")){ i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ trackFileName = args[i]; }else{ die("-track requires a filename"); } } else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(blockOutputType != -1){ die("Only one block output type argument is allowed."); } if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){ blockOutputType = BLOX_GABRIEL; } else if(args[i].equalsIgnoreCase("GAM")){ blockOutputType = BLOX_4GAM; } else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){ blockOutputType = BLOX_SPINE; } else if(args[i].equalsIgnoreCase("ALL")) { blockOutputType = BLOX_ALL; } } else { //defaults to SFS output blockOutputType = BLOX_GABRIEL; i--; } } else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) { outputDprime = true; } else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){ outputCheck = true; } else if (args[i].equalsIgnoreCase("-indcheck")){ individualCheck = true; } else if (args[i].equalsIgnoreCase("-mendel")){ mendel = true; } else if (args[i].equalsIgnoreCase("-malehets")){ malehets = true; } else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) { i++; maxDistance = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) { //batch mode i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(batchFileName != null){ argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used"); } batchFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-hapthresh")) { i++; hapThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-spacing")) { i++; spacingThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-minMAF")) { i++; minimumMAF = getDoubleArg(args,i,0,0.5); } else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) { i++; minimumGenoPercent = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-hwcutoff")) { i++; hwCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-maxMendel") ) { i++; maxMendel = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-missingcutoff")) { i++; missingCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-assoctdt")) { assocTDT = true; } else if(args[i].equalsIgnoreCase("-assoccc")) { assocCC = true; } else if(args[i].equalsIgnoreCase("-randomcc")){ assocCC = true; randomizeAffection = true; } else if(args[i].equalsIgnoreCase("-ldcolorscheme")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(args[i].equalsIgnoreCase("default")){ Options.setLDColorScheme(STD_SCHEME); } else if(args[i].equalsIgnoreCase("RSQ")){ Options.setLDColorScheme(RSQ_SCHEME); } else if(args[i].equalsIgnoreCase("DPALT") ){ Options.setLDColorScheme(WMF_SCHEME); } else if(args[i].equalsIgnoreCase("GAB")) { Options.setLDColorScheme(GAB_SCHEME); } else if(args[i].equalsIgnoreCase("GAM")) { Options.setLDColorScheme(GAM_SCHEME); } else if(args[i].equalsIgnoreCase("GOLD")) { Options.setLDColorScheme(GOLD_SCHEME); } } else { //defaults to STD color scheme Options.setLDColorScheme(STD_SCHEME); i--; } } else if(args[i].equalsIgnoreCase("-blockCutHighCI")) { i++; cutHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockCutLowCI")) { i++; cutLowCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockMafThresh")) { i++; mafThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockRecHighCI")) { i++; recHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockInformFrac")) { i++; informFrac = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-block4GamCut")) { i++; fourGameteCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockSpineDP")) { i++; spineDP = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-permtests")) { i++; doPermutationTest = true; permutationCount = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-customassoc")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ customAssocTestsFileName = args[i]; }else{ die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-aggressiveTagging")) { tagging = Tagger.AGGRESSIVE_TRIPLE; } else if (args[i].equalsIgnoreCase("-pairwiseTagging")){ tagging = Tagger.PAIRWISE_ONLY; } else if (args[i].equalsIgnoreCase("-printalltags")){ Options.setPrintAllTags(true); } else if(args[i].equalsIgnoreCase("-maxNumTags")){ i++; maxNumTags = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) { i++; tagRSquaredCutOff = getDoubleArg(args,i,0,1); } else if (args[i].equalsIgnoreCase("-dontaddtags")){ findTags = false; } else if(args[i].equalsIgnoreCase("-tagLODCutoff")) { i++; Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000)); } else if(args[i].equalsIgnoreCase("-includeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die(args[i-1] + " requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceIncludeTags = new Vector(); while(str.hasMoreTokens()) { forceIncludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-includeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceIncludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-excludeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die("-excludeTags requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceExcludeTags = new Vector(); while(str.hasMoreTokens()) { forceExcludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-excludeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceExcludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-captureAlleles")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { captureAllelesFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-designScores")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { designScoresFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-mintagdistance")){ i++; minTagDistance = args[i]; } else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { chromosomeArg =args[i]; }else { die(args[i-1] + " requires a chromosome name"); } if(!(chromosomeArg.equalsIgnoreCase("X")) && !(chromosomeArg.equalsIgnoreCase("Y"))){ try{ if (Integer.parseInt(chromosomeArg) > 22){ die("-chromosome requires a chromsome name of 1-22, X, or Y"); } }catch(NumberFormatException nfe){ die("-chromosome requires a chromsome name of 1-22, X, or Y"); } } } else if(args[i].equalsIgnoreCase("-population")){ i++; if(!(i>=args.length) && !(args[i].charAt(0)== '-')) { populationArg = args[i]; }else { die(args[i-1] + "requires a population name"); } } else if(args[i].equalsIgnoreCase("-startpos")){ i++; startPos = args[i]; } else if(args[i].equalsIgnoreCase("-endPos")){ i++; endPos = args[i]; } else if(args[i].equalsIgnoreCase("-release")){ i++; release = args[i]; } else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) { quietMode = true; } else if(args[i].equalsIgnoreCase("-gzip")){ Options.setGzip(true); } else { die("invalid parameter specified: " + args[i]); } } if (logName != null){ logString = "*****************************************************\n" + TITLE_STRING + "\tJava Version: " + JAVA_VERSION + "\n*****************************************************\n\n\n" + "Arguments:\t"; for (int i = 0; i < args.length; i++){ logString = logString + args[i] + "\t"; } logString = logString + "\n\n"; } int countOptions = 0; if(pedFileName != null) { countOptions++; } if(hapsFileName != null) { countOptions++; } if(hapmapFileName != null) { countOptions++; } if(phasedhmpdataFileName != null) { countOptions++; if(phasedhmpsampleFileName == null){ die("You must specify a sample file for phased hapmap input."); }else if(phasedhmplegendFileName == null){ die("You must specify a legend file for phased hapmap input."); } } if(phasedhapmapDownload) { countOptions++; } if(plinkFileName != null){ countOptions++; if(mapFileName == null){ die("You must specify a map file for plink format input."); } } if(batchFileName != null) { countOptions++; } if(countOptions > 1) { die("Only one genotype input file may be specified on the command line."); } else if(countOptions == 0 && nogui) { die("You must specify a genotype input file."); } //mess with vars, set defaults, etc if(skipCheck) { argHandlerMessages.add("Skipping genotype file check"); } if(maxDistance == -1){ maxDistance = MAXDIST_DEFAULT; }else{ argHandlerMessages.add("Max LD comparison distance = " +maxDistance + "kb"); } Options.setMaxDistance(maxDistance); if(hapThresh != -1) { Options.setHaplotypeDisplayThreshold(hapThresh); argHandlerMessages.add("Haplotype display threshold = " + hapThresh); } if(minimumMAF != -1) { CheckData.mafCut = minimumMAF; argHandlerMessages.add("Minimum MAF = " + minimumMAF); } if(minimumGenoPercent != -1) { CheckData.failedGenoCut = (int)(minimumGenoPercent*100); argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent); } if(hwCutoff != -1) { CheckData.hwCut = hwCutoff; argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff); } if(maxMendel != -1) { CheckData.numMendErrCut = maxMendel; argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel); } if(spacingThresh != -1) { Options.setSpacingThreshold(spacingThresh); argHandlerMessages.add("LD display spacing value = "+spacingThresh); } if(missingCutoff != -1) { Options.setMissingThreshold(missingCutoff); argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff); } if(cutHighCI != -1) { FindBlocks.cutHighCI = cutHighCI; } if(cutLowCI != -1) { FindBlocks.cutLowCI = cutLowCI; } if(mafThresh != -1) { FindBlocks.mafThresh = mafThresh; } if(recHighCI != -1) { FindBlocks.recHighCI = recHighCI; } if(informFrac != -1) { FindBlocks.informFrac = informFrac; } if(fourGameteCutoff != -1) { FindBlocks.fourGameteCutoff = fourGameteCutoff; } if(spineDP != -1) { FindBlocks.spineDP = spineDP; } if(assocTDT) { Options.setAssocTest(ASSOC_TRIO); }else if(assocCC) { Options.setAssocTest(ASSOC_CC); } if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) { die("A marker info file must be specified when performing association tests."); } if(doPermutationTest) { if(!assocCC && !assocTDT) { die("An association test type must be specified for permutation tests to be performed."); } } if(customAssocTestsFileName != null) { if(!assocCC && !assocTDT) { die("An association test type must be specified when using a custom association test file."); } if(infoFileName == null) { die("A marker info file must be specified when using a custom association test file."); } } if(tagging != Tagger.NONE) { if(infoFileName == null && hapmapFileName == null && batchFileName == null && phasedhmpdataFileName == null && !phasedhapmapDownload) { die("A marker info file must be specified when tagging."); } if(forceExcludeTags == null) { forceExcludeTags = new Vector(); } else if (forceExcludeFileName != null) { die("-excludeTags and -excludeTagsFile cannot both be used"); } if(forceExcludeFileName != null) { File excludeFile = new File(forceExcludeFileName); forceExcludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(excludeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceExcludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -excludeTagsFile."); } } if(forceIncludeTags == null ) { forceIncludeTags = new Vector(); } else if (forceIncludeFileName != null) { die("-includeTags and -includeTagsFile cannot both be used"); } if(forceIncludeFileName != null) { File includeFile = new File(forceIncludeFileName); forceIncludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(includeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceIncludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -includeTagsFile."); } } if (captureAllelesFileName != null) { File captureFile = new File(captureAllelesFileName); captureAlleleTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(captureFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ line = line.trim(); captureAlleleTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (designScoresFileName != null) { File designFile = new File(designScoresFileName); designScores = new Hashtable(1,1); try { BufferedReader br = new BufferedReader(new FileReader(designFile)); String line; int lines = 0; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ StringTokenizer st = new StringTokenizer(line); int length = st.countTokens(); if (length != 2){ die("Invalid formatting on line " + lines); } String marker = st.nextToken(); Double score = new Double(st.nextToken()); designScores.put(marker,score); } lines++; } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (minTagDistance != null) { try{ if (Integer.parseInt(minTagDistance) < 0){ die("minimum tag distance cannot be negative"); } }catch(NumberFormatException nfe){ die("minimum tag distance must be a positive integer"); } Options.setTaggerMinDistance(Integer.parseInt(minTagDistance)); } //check that there isn't any overlap between include/exclude lists Vector tempInclude = (Vector) forceIncludeTags.clone(); tempInclude.retainAll(forceExcludeTags); if(tempInclude.size() > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < tempInclude.size(); i++) { String s = (String) tempInclude.elementAt(i); sb.append(s).append(","); } die("The following markers appear in both the include and exclude lists: " + sb.toString()); } if(tagRSquaredCutOff != -1) { Options.setTaggerRsqCutoff(tagRSquaredCutOff); } } else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) { die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without a tagging option"); } if(chromosomeArg != null && hapmapFileName != null) { argHandlerMessages.add("-chromosome flag ignored when loading hapmap file"); chromosomeArg = null; } if(chromosomeArg != null) { Chromosome.setDataChrom("chr" + chromosomeArg); }else{ chromosomeArg = ""; } if (phasedhapmapDownload){ if (chromosomeArg == null){ die("-phasedhapmapdl requires a chromosome specification"); }else if (!(populationArg.equalsIgnoreCase("CEU") || populationArg.equalsIgnoreCase("YRI") || populationArg.equalsIgnoreCase("CHB+JPT"))){ die("-phasedhapmapdl requires a population specification of CEU, YRI, or CHB+JPT"); } if (Integer.parseInt(chromosomeArg) < 1 && Integer.parseInt(chromosomeArg) > 22){ if (!(chromosomeArg.equalsIgnoreCase("X")) && !(chromosomeArg.equalsIgnoreCase("Y"))){ die("-chromosome must be betweeen 1 and 22, X, or Y"); } } try{ if (Integer.parseInt(startPos) > Integer.parseInt(endPos)){ die("-endpos must be greater then -startpos"); } }catch(NumberFormatException nfe){ die("-startpos and -endpos must be integer values"); } if (release == null){ release = "21"; } if (!(release.equals("21")) && !(release.startsWith("16"))){ die("release must be either 16a or 21"); } } }
1,109,698
public void setAttribute(String name, Object value) { super.setAttribute( name, value.toString() ); }
public void setAttribute(String name, Object value) { super.setAttribute( name, value.toString() ); }
1,109,700
public void testParserCache2() throws Exception { // no default namespace setUp("nsFilterTest.jelly"); Script script = jelly.compileScript(); script.run(context,xmlOutput); assertTrue("should have no var when default namspace is not set", context.getVariable("usedDefaultNamespace") == null); // now we have a default namespace, so we // should see a variable, despite the XMLParser cache jelly.setDefaultNamespaceURI("jelly:core"); script = jelly.compileScript(); script.run(context,xmlOutput); assertTrue("should have var when default namspace is set", context.getVariable("usedDefaultNamespace").equals("tru")); }
public void testParserCache2() throws Exception { // no default namespace setUp("nsFilterTest.jelly"); Script script = jelly.compileScript(); script.run(context,xmlOutput); assertTrue("should have no var when default namspace is not set", context.getVariable("usedDefaultNamespace") == null); // now we have a default namespace, so we // should see a variable, despite the XMLParser cache jelly.setDefaultNamespaceURI("jelly:core"); script = jelly.compileScript(); script.run(context,xmlOutput); assertTrue("should have var when default namspace is set", context.getVariable("usedDefaultNamespace").equals("true")); }
1,109,701
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
public Vector prepareHapsInput(File infile) throws IOException, HaploViewException, PedFileException { //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
1,109,702
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. isHaps = true; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
1,109,703
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
1,109,704
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
1,109,705
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
1,109,706
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
void prepareHapsInput(File infile) throws IOException, HaploViewException{ //this method is called to suck in data from a file (its only argument) //of genotypes and sets up the Chromosome objects. String currentLine; Vector chroms = new Vector(); byte[] genos = new byte[0]; String ped, indiv; if(infile.length() < 1){ throw new HaploViewException("Genotype file is empty or does not exist: " + infile.getName()); } //read the file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; int numTokens = 0; boolean even = true; while ((currentLine = in.readLine()) != null){ lineCount++; //each line is expected to be of the format: //ped indiv geno geno geno geno... if (currentLine.length() == 0){ //skip blank lines continue; } even = !even; StringTokenizer st = new StringTokenizer(currentLine); //first two tokens are expected to be ped, indiv if (st.countTokens() >2){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 3 columns."); } //all other tokens are loaded into a vector (they should all be genotypes) genos = new byte[st.countTokens()]; int q = 0; if (numTokens == 0){ numTokens = st.countTokens(); } if (numTokens != st.countTokens()){ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have an incorrect number of entries"); } while (st.hasMoreTokens()){ String thisGenotype = (String)st.nextElement(); if (thisGenotype.equals("h")) { genos[q] = 9; }else{ try{ genos[q] = Byte.parseByte(thisGenotype); }catch (NumberFormatException nfe){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + thisGenotype + "\" on line " + lineCount + " not allowed."); } } if (genos[q] < 0 || genos[q] > 9){ throw new HaploViewException("Genotype file input error:\ngenotype value \"" + genos[q] + "\" on line " + lineCount + " not allowed."); } q++; } //a Chromosome is created and added to a vector of chromosomes. //this is what is evetually returned. chroms.add(new Chromosome(ped, indiv, genos, infile.getName(), 0)); } if (!even){ //we're missing a line here throw new HaploViewException("Genotype file appears to have an odd number of lines.\n"+ "Each individual is required to have two chromosomes"); } chromosomes = chroms; //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
1,109,707
public void doTag(final XMLOutput output) throws Exception { String name = getName(); if ( name == null ) { name = toString(); } // #### we need to redirect the output to a TestListener // or something? TestCase testCase = new TestCase(name) { protected void runTest() throws Throwable { invokeBody(output); } }; // lets find the test suite TestSuite suite = getSuite(); if ( suite == null ) { throw new JellyException( "Could not find a TestSuite to add this test to. This tag should be inside a <test:suite> tag" ); } suite.addTest(testCase); }
public void doTag(final XMLOutput output) throws Exception { String name = getName(); if ( name == null ) { name = toString(); } // #### we need to redirect the output to a TestListener // or something? TestCase testCase = new TestCase(name) { protected void runTest() throws Throwable { JellyContext newContext = new JellyContext( context ); getBody().run(newContext, output); } }; // lets find the test suite TestSuite suite = getSuite(); if ( suite == null ) { throw new JellyException( "Could not find a TestSuite to add this test to. This tag should be inside a <test:suite> tag" ); } suite.addTest(testCase); }
1,109,709
protected void runTest() throws Throwable { invokeBody(output); }
protected void runTest() throws Throwable { JellyContext newContext = new JellyContext( context ); getBody().run(newContext, output); }
1,109,710
private void processFile(String fileName, int fileType, String infoFileName){ try { int outputType; long maxDistance; HaploData textData; File OutputFile; File inputFile; if(!arg_quiet && fileName != null){ System.out.println("Using data file " + fileName); } inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } maxDistance = this.arg_distance * 1000; outputType = this.arg_output; textData = new HaploData(0); Vector result = null; if(fileType == HAPS){ //read in haps file textData.prepareHapsInput(inputFile); } else if (fileType == PED) { //read in ped file /* if(this.arg_ignoreMarkers.size()>0) { for(int i=0;i<this.arg_ignoreMarkers.size();i++){ int index = Integer.parseInt((String)this.arg_ignoreMarkers.get(i)); if(index>0 && index<markerResultArray.length){ markerResultArray[index] = false; if(!this.arg_quiet) { System.out.println("Ignoring marker " + (index)); } } } }*/ result = textData.linkageToChrom(inputFile, 3, arg_skipCheck); }else{ //read in hapmapfile result = textData.linkageToChrom(inputFile,4,arg_skipCheck); } File infoFile; if(infoFileName.equals("")) { infoFile = null; }else{ infoFile = new File(infoFileName); } if (result != null){ textData.prepareMarkerInput(infoFile,maxDistance,textData.getPedFile().getHMInfo()); }else{ textData.prepareMarkerInput(infoFile,maxDistance,null); } if(!arg_quiet && infoFile != null){ System.out.println("Using marker file " + infoFile.getName()); } if(this.arg_showCheck && result != null) { CheckDataPanel cp = new CheckDataPanel(textData, false); cp.printTable(null); } if(this.arg_check && result != null){ CheckDataPanel cp = new CheckDataPanel(textData, false); cp.printTable(new File (fileName + ".CHECK")); } Vector cust = new Vector(); if(outputType != -1){ textData.generateDPrimeTable(); Haplotype[][] haplos; switch(outputType){ case BLOX_GABRIEL: OutputFile = new File(fileName + ".GABRIELblocks"); break; case BLOX_4GAM: OutputFile = new File(fileName + ".4GAMblocks"); break; case BLOX_SPINE: OutputFile = new File(fileName + ".SPINEblocks"); break; case BLOX_CUSTOM: OutputFile = new File(fileName + ".CUSTblocks"); //read in the blocks file File blocksFile = new File(arg_blockfile); cust = textData.readBlocks(blocksFile); break; default: OutputFile = new File(fileName + ".GABRIELblocks"); break; } //this handles output type ALL int start = 0; int stop = Chromosome.getSize(); if(outputType == BLOX_ALL) { OutputFile = new File(fileName + ".GABRIELblocks"); textData.guessBlocks(BLOX_GABRIEL); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".4GAMblocks"); textData.guessBlocks(BLOX_4GAM); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".SPINEblocks"); textData.guessBlocks(BLOX_SPINE); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); }else{ textData.guessBlocks(outputType, cust); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); } } if(this.arg_dprime) { OutputFile = new File(fileName + ".DPRIME"); if (textData.dpTable != null){ textData.saveDprimeToText(OutputFile, TABLE_TYPE, 0, Chromosome.getSize()); }else{ textData.saveDprimeToText(OutputFile, LIVE_TYPE, 0, Chromosome.getSize()); } } if (this.arg_png || this.arg_smallpng){ OutputFile = new File(fileName + ".LD.PNG"); if (textData.dpTable == null){ textData.generateDPrimeTable(); textData.guessBlocks(BLOX_CUSTOM, new Vector()); } if (this.arg_trackName != null){ textData.readAnalysisTrack(new File(arg_trackName)); } DPrimeDisplay dpd = new DPrimeDisplay(textData); BufferedImage i = dpd.export(0,Chromosome.getSize(),this.arg_smallpng); try{ Jimi.putImage("image/png", i, OutputFile.getName()); }catch(JimiException je){ System.out.println(je.getMessage()); } } //if(fileType){ //TDT.calcTrioTDT(textData.chromosomes); //TODO: Deal with this. why do we calc TDT? and make sure not to do it except when appropriate //} } catch(IOException e){ System.err.println("An error has occured. This probably has to do with file input or output"); } catch(HaploViewException e){ System.err.println(e.getMessage()); } catch(PedFileException pfe) { System.err.println(pfe.getMessage()); } }
private void processFile(String fileName, int fileType, String infoFileName){ try { int outputType; long maxDistance; HaploData textData; File OutputFile; File inputFile; if(!arg_quiet && fileName != null){ System.out.println("Using data file " + fileName); } inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } maxDistance = this.arg_distance * 1000; outputType = this.arg_output; textData = new HaploData(); Vector result = null; if(fileType == HAPS){ //read in haps file textData.prepareHapsInput(inputFile); } else if (fileType == PED) { //read in ped file /* if(this.arg_ignoreMarkers.size()>0) { for(int i=0;i<this.arg_ignoreMarkers.size();i++){ int index = Integer.parseInt((String)this.arg_ignoreMarkers.get(i)); if(index>0 && index<markerResultArray.length){ markerResultArray[index] = false; if(!this.arg_quiet) { System.out.println("Ignoring marker " + (index)); } } } }*/ result = textData.linkageToChrom(inputFile, 3, arg_skipCheck); }else{ //read in hapmapfile result = textData.linkageToChrom(inputFile,4,arg_skipCheck); } File infoFile; if(infoFileName.equals("")) { infoFile = null; }else{ infoFile = new File(infoFileName); } if (result != null){ textData.prepareMarkerInput(infoFile,maxDistance,textData.getPedFile().getHMInfo()); }else{ textData.prepareMarkerInput(infoFile,maxDistance,null); } if(!arg_quiet && infoFile != null){ System.out.println("Using marker file " + infoFile.getName()); } if(this.arg_showCheck && result != null) { CheckDataPanel cp = new CheckDataPanel(textData, false); cp.printTable(null); } if(this.arg_check && result != null){ CheckDataPanel cp = new CheckDataPanel(textData, false); cp.printTable(new File (fileName + ".CHECK")); } Vector cust = new Vector(); if(outputType != -1){ textData.generateDPrimeTable(); Haplotype[][] haplos; switch(outputType){ case BLOX_GABRIEL: OutputFile = new File(fileName + ".GABRIELblocks"); break; case BLOX_4GAM: OutputFile = new File(fileName + ".4GAMblocks"); break; case BLOX_SPINE: OutputFile = new File(fileName + ".SPINEblocks"); break; case BLOX_CUSTOM: OutputFile = new File(fileName + ".CUSTblocks"); //read in the blocks file File blocksFile = new File(arg_blockfile); cust = textData.readBlocks(blocksFile); break; default: OutputFile = new File(fileName + ".GABRIELblocks"); break; } //this handles output type ALL int start = 0; int stop = Chromosome.getSize(); if(outputType == BLOX_ALL) { OutputFile = new File(fileName + ".GABRIELblocks"); textData.guessBlocks(BLOX_GABRIEL); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".4GAMblocks"); textData.guessBlocks(BLOX_4GAM); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); OutputFile = new File(fileName + ".SPINEblocks"); textData.guessBlocks(BLOX_SPINE); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); }else{ textData.guessBlocks(outputType, cust); haplos = textData.generateHaplotypes(textData.blocks, 1); textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); } } if(this.arg_dprime) { OutputFile = new File(fileName + ".DPRIME"); if (textData.dpTable != null){ textData.saveDprimeToText(OutputFile, TABLE_TYPE, 0, Chromosome.getSize()); }else{ textData.saveDprimeToText(OutputFile, LIVE_TYPE, 0, Chromosome.getSize()); } } if (this.arg_png || this.arg_smallpng){ OutputFile = new File(fileName + ".LD.PNG"); if (textData.dpTable == null){ textData.generateDPrimeTable(); textData.guessBlocks(BLOX_CUSTOM, new Vector()); } if (this.arg_trackName != null){ textData.readAnalysisTrack(new File(arg_trackName)); } DPrimeDisplay dpd = new DPrimeDisplay(textData); BufferedImage i = dpd.export(0,Chromosome.getSize(),this.arg_smallpng); try{ Jimi.putImage("image/png", i, OutputFile.getName()); }catch(JimiException je){ System.out.println(je.getMessage()); } } //if(fileType){ //TDT.calcTrioTDT(textData.chromosomes); //TODO: Deal with this. why do we calc TDT? and make sure not to do it except when appropriate //} } catch(IOException e){ System.err.println("An error has occured. This probably has to do with file input or output"); } catch(HaploViewException e){ System.err.println(e.getMessage()); } catch(PedFileException pfe) { System.err.println(pfe.getMessage()); } }
1,109,712
void saveDprimeToText(){ fc.setSelectedFile(null); try{ fc.setSelectedFile(null); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { new TextMethods().saveDprimeToText(theData.getFilteredTable(theData.dPrimeTable), fc.getSelectedFile(), infoKnown, new Vector()); } }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } }
void saveDprimeToText(){ fc.setSelectedFile(null); try{ fc.setSelectedFile(null); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { theData.saveDprimeToText(theData.getFilteredTable(theData.dPrimeTable), fc.getSelectedFile(), infoKnown, new Vector()); } }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } }
1,109,713
public int skipNext(int amount) throws FetchException { if (amount <= 0) { if (amount < 0) { throw new IllegalArgumentException("Cannot skip negative amount: " + amount); } return 0; } ResultSet rs = mResultSet; if (rs == null) { return 0; } mHasNext = true; int actual = 0; while (amount > 0) { try { if (rs.next()) { actual++; amount--; } else { mHasNext = false; close(); break; } } catch (SQLException e) { throw mStorage.getJDBCRepository().toFetchException(e); } } return actual; }
public int skipNext(int amount) throws FetchException { if (amount <= 0) { if (amount < 0) { throw new IllegalArgumentException("Cannot skip negative amount: " + amount); } return 0; } ResultSet rs = mResultSet; if (rs == null) { return 0; } mHasNext = true; int actual = 0; while (amount > 0) { try { if (rs.next()) { actual++; amount--; } else { mHasNext = false; close(); break; } } catch (SQLException e) { throw mStorage.getJDBCRepository().toFetchException(e); } } return actual; }
1,109,714
public int skipNext(int amount) throws FetchException { if (amount <= 0) { if (amount < 0) { throw new IllegalArgumentException("Cannot skip negative amount: " + amount); } return 0; } ResultSet rs = mResultSet; if (rs == null) { return 0; } mHasNext = true; int actual = 0; while (amount > 0) { try { if (rs.next()) { actual++; amount--; } else { mHasNext = false; close(); break; } } catch (SQLException e) { throw mStorage.getJDBCRepository().toFetchException(e); } } return actual; }
public int skipNext(int amount) throws FetchException { if (amount <= 0) { if (amount < 0) { throw new IllegalArgumentException("Cannot skip negative amount: " + amount); } return 0; } ResultSet rs = mResultSet; if (rs == null) { return 0; } mHasNext = true; int actual = 0; while (amount > 0) { try { if (rs.next()) { actual++; amount--; } else { mHasNext = false; close(); break; } } catch (SQLException e) { throw mStorage.getJDBCRepository().toFetchException(e); } } return actual; }
1,109,715
double max() default Double.MAX_VALUE;
double max() default Double.POSITIVE_INFINITY;
1,109,717
double min() default Double.MIN_VALUE;
double min() default Double.NEGATIVE_INFINITY;
1,109,718
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
public static void initODMG( String user, String passwd, PVDatabase dbDesc ) throws PhotovaultException { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
1,109,719
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } else { log.error( "Could not open database connection" ); try { db.close(); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } catch (ODMGException e ) { log.error( "Error closing database" ); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } catch (ODMGException e ) { log.error( "Error closing database" ); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); } return ( success ); } try { PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey); broker.beginTransaction(); Connection con = broker.serviceConnectionManager().getConnection(); broker.commitTransaction(); broker.close(); } catch (Exception ex) { Throwable rootCause = ex; while ( rootCause.getCause() != null ) { rootCause = rootCause.getCause(); } log.error( rootCause.getMessage() ); if ( rootCause instanceof SQLException ) { if ( rootCause instanceof EmbedSQLException ) { throw new PhotovaultException( "Cannot start database.\n" + "Do you have another instance of Photovault running?", rootCause ); } if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) { throw new PhotovaultException( "Cannot log in to MySQL database", rootCause ); } } throw new PhotovaultException( "Unknown error while starting database:\n" + rootCause.getMessage(), rootCause ); }
1,109,720
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Exception t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
1,109,721
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
1,109,722
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } return ( success ); }
public static boolean initODMG( String user, String passwd, PVDatabase dbDesc ) { getODMGImplementation(); // Find the connection repository info ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); PBKey connKey = cr.getStandardPBKeyForJcdAlias( "pv" ); JdbcConnectionDescriptor connDesc = cr.getDescriptor( connKey ); // Set up the OJB connection with parameters from photovault.properties if ( dbDesc.getInstanceType() == PVDatabase.TYPE_EMBEDDED ) { connDesc.setDriver( "org.apache.derby.jdbc.EmbeddedDriver" ); connDesc.setDbms( "derby" ); connDesc.setSubProtocol( "derby" ); connDesc.setDbAlias( "photovault" ); File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" ); System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() ); } else { String dbhost = dbDesc.getDbHost(); String dbname = dbDesc.getDbName(); connDesc.setDbAlias( "//" + dbhost + "/" + dbname ); connDesc.setUserName( user ); connDesc.setPassWord( passwd ); } // Open the database connection db = odmg.newDatabase(); boolean success = false; try { log.debug( "Opening database" ); db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE ); log.debug( "Success!!!" ); } catch ( Exception e ) { log.error( "Failed to get connection: " + e.getMessage() ); e.printStackTrace(); } // Test the connection by fetching something try { PhotoFolder folder = PhotoFolder.getRoot(); if ( folder != null ) { success = true; } else { log.error( "Could not open database connection" ); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } } catch ( Throwable t ) { log.error( "Could not open database connection" ); log.error( t.getMessage() ); t.printStackTrace(); try { db.close(); } catch (ODMGException e ) { log.error( "Error closing database" ); } } }
1,109,723
public java.util.Date getEndDate() { return endDate; }
public java.util.Date getEndDate() { return endDate != null ? (java.util.Date) endDate.clone() : null; }
1,109,724
public java.util.Date getStartDate() { return startDate; }
public java.util.Date getStartDate() { return startDate != null ? (java.util.Date)startDate.clone() : null; }
1,109,725
public void setEndDate( java.util.Date date ) { endDate = date; modified(); }
public void setEndDate( java.util.Date date ) { endDate = (date != null) ? (java.util.Date) date.clone() : null; modified(); }
1,109,726
public void setStartDate( java.util.Date date ) { startDate = date; modified(); }
public void setStartDate( java.util.Date date ) { startDate = (date != null) ? (java.util.Date)date.clone() : null; modified(); }
1,109,727
public void stateChanged(ChangeEvent e) { int tabNum = tabs.getSelectedIndex(); if (tabNum == VIEW_D_NUM || tabNum == VIEW_HAP_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(true); }else if (tabNum == VIEW_TDT_NUM || tabNum == VIEW_CHECK_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(false); }else{ exportMenuItems[0].setEnabled(false); exportMenuItems[1].setEnabled(false); } if (tabNum == VIEW_D_NUM){ keyMenu.setEnabled(true); }else{ keyMenu.setEnabled(false); } viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ //first store up the current blocks Vector currentBlocks = new Vector(); for (int blocks = 0; blocks < theData.blocks.size(); blocks++){ int thisBlock[] = (int[]) theData.blocks.elementAt(blocks); int thisBlockReal[] = new int[thisBlock.length]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlockReal[marker] = Chromosome.realIndex[thisBlock[marker]]; } currentBlocks.add(thisBlockReal); } window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,CheckDataPanel.STATUS_COL)).booleanValue(); } Chromosome.doFilter(markerResults); //after editing the filtered marker list, needs to be prodded into //resizing correctly Dimension size = dPrimeDisplay.getSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } dPrimeDisplay.colorDPrime(currentScheme); hapDisplay.theData = theData; if (currentBlockDef != BLOX_CUSTOM){ changeBlocks(currentBlockDef); }else{ //adjust the blocks Vector theBlocks = new Vector(); for (int x = 0; x < currentBlocks.size(); x++){ Vector goodies = new Vector(); int currentBlock[] = (int[])currentBlocks.elementAt(x); for (int marker = 0; marker < currentBlock.length; marker++){ for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input that are "good" from checkdata //we also realign the input file to the current "good" subset since input is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == currentBlock[marker]){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlock[marker] = ((Integer)goodies.elementAt(marker)).intValue(); } if (thisBlock.length > 1){ theBlocks.add(thisBlock); } } theData.guessBlocks(BLOX_CUSTOM, theBlocks); } if (tdtPanel != null){ tdtPanel.refreshTable(); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } if (hapDisplay != null && theData.blocksChanged){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } hapScroller.setViewportView(hapDisplay); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); theData.blocksChanged = false; } }
public void stateChanged(ChangeEvent e) { int tabNum = tabs.getSelectedIndex(); if (tabNum == VIEW_D_NUM || tabNum == VIEW_HAP_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(true); }else if (tabNum == VIEW_TDT_NUM || tabNum == VIEW_CHECK_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(false); }else{ exportMenuItems[0].setEnabled(false); exportMenuItems[1].setEnabled(false); } if (tabNum == VIEW_D_NUM){ keyMenu.setEnabled(true); }else{ keyMenu.setEnabled(false); } viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ //first store up the current blocks Vector currentBlocks = new Vector(); for (int blocks = 0; blocks < theData.blocks.size(); blocks++){ int thisBlock[] = (int[]) theData.blocks.elementAt(blocks); int thisBlockReal[] = new int[thisBlock.length]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlockReal[marker] = Chromosome.realIndex[thisBlock[marker]]; } currentBlocks.add(thisBlockReal); } window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,CheckDataPanel.STATUS_COL)).booleanValue(); } Chromosome.doFilter(markerResults); //after editing the filtered marker list, needs to be prodded into //resizing correctly dPrimeDisplay.computePreferredSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } dPrimeDisplay.colorDPrime(currentScheme); hapDisplay.theData = theData; if (currentBlockDef != BLOX_CUSTOM){ changeBlocks(currentBlockDef); }else{ //adjust the blocks Vector theBlocks = new Vector(); for (int x = 0; x < currentBlocks.size(); x++){ Vector goodies = new Vector(); int currentBlock[] = (int[])currentBlocks.elementAt(x); for (int marker = 0; marker < currentBlock.length; marker++){ for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input that are "good" from checkdata //we also realign the input file to the current "good" subset since input is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == currentBlock[marker]){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlock[marker] = ((Integer)goodies.elementAt(marker)).intValue(); } if (thisBlock.length > 1){ theBlocks.add(thisBlock); } } theData.guessBlocks(BLOX_CUSTOM, theBlocks); } if (tdtPanel != null){ tdtPanel.refreshTable(); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } if (hapDisplay != null && theData.blocksChanged){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } hapScroller.setViewportView(hapDisplay); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); theData.blocksChanged = false; } }
1,109,728
public void stateChanged(ChangeEvent e) { int tabNum = tabs.getSelectedIndex(); if (tabNum == VIEW_D_NUM || tabNum == VIEW_HAP_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(true); }else if (tabNum == VIEW_TDT_NUM || tabNum == VIEW_CHECK_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(false); }else{ exportMenuItems[0].setEnabled(false); exportMenuItems[1].setEnabled(false); } if (tabNum == VIEW_D_NUM){ keyMenu.setEnabled(true); }else{ keyMenu.setEnabled(false); } viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ //first store up the current blocks Vector currentBlocks = new Vector(); for (int blocks = 0; blocks < theData.blocks.size(); blocks++){ int thisBlock[] = (int[]) theData.blocks.elementAt(blocks); int thisBlockReal[] = new int[thisBlock.length]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlockReal[marker] = Chromosome.realIndex[thisBlock[marker]]; } currentBlocks.add(thisBlockReal); } window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,CheckDataPanel.STATUS_COL)).booleanValue(); } Chromosome.doFilter(markerResults); //after editing the filtered marker list, needs to be prodded into //resizing correctly Dimension size = dPrimeDisplay.getSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } dPrimeDisplay.colorDPrime(currentScheme); hapDisplay.theData = theData; if (currentBlockDef != BLOX_CUSTOM){ changeBlocks(currentBlockDef); }else{ //adjust the blocks Vector theBlocks = new Vector(); for (int x = 0; x < currentBlocks.size(); x++){ Vector goodies = new Vector(); int currentBlock[] = (int[])currentBlocks.elementAt(x); for (int marker = 0; marker < currentBlock.length; marker++){ for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input that are "good" from checkdata //we also realign the input file to the current "good" subset since input is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == currentBlock[marker]){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlock[marker] = ((Integer)goodies.elementAt(marker)).intValue(); } if (thisBlock.length > 1){ theBlocks.add(thisBlock); } } theData.guessBlocks(BLOX_CUSTOM, theBlocks); } if (tdtPanel != null){ tdtPanel.refreshTable(); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } if (hapDisplay != null && theData.blocksChanged){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } hapScroller.setViewportView(hapDisplay); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); theData.blocksChanged = false; } }
public void stateChanged(ChangeEvent e) { int tabNum = tabs.getSelectedIndex(); if (tabNum == VIEW_D_NUM || tabNum == VIEW_HAP_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(true); }else if (tabNum == VIEW_TDT_NUM || tabNum == VIEW_CHECK_NUM){ exportMenuItems[0].setEnabled(true); exportMenuItems[1].setEnabled(false); }else{ exportMenuItems[0].setEnabled(false); exportMenuItems[1].setEnabled(false); } if (tabNum == VIEW_D_NUM){ keyMenu.setEnabled(true); }else{ keyMenu.setEnabled(false); } viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ //first store up the current blocks Vector currentBlocks = new Vector(); for (int blocks = 0; blocks < theData.blocks.size(); blocks++){ int thisBlock[] = (int[]) theData.blocks.elementAt(blocks); int thisBlockReal[] = new int[thisBlock.length]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlockReal[marker] = Chromosome.realIndex[thisBlock[marker]]; } currentBlocks.add(thisBlockReal); } window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,CheckDataPanel.STATUS_COL)).booleanValue(); } Chromosome.doFilter(markerResults); //after editing the filtered marker list, needs to be prodded into //resizing correctly Dimension size = dPrimeDisplay.getSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } dPrimeDisplay.colorDPrime(currentScheme); hapDisplay.theData = theData; if (currentBlockDef != BLOX_CUSTOM){ changeBlocks(currentBlockDef); }else{ //adjust the blocks Vector theBlocks = new Vector(); for (int x = 0; x < currentBlocks.size(); x++){ Vector goodies = new Vector(); int currentBlock[] = (int[])currentBlocks.elementAt(x); for (int marker = 0; marker < currentBlock.length; marker++){ for (int y = 0; y < Chromosome.realIndex.length; y++){ //we only keep markers from the input that are "good" from checkdata //we also realign the input file to the current "good" subset since input is //indexed of all possible markers in the dataset if (Chromosome.realIndex[y] == currentBlock[marker]){ goodies.add(new Integer(y)); } } } int thisBlock[] = new int[goodies.size()]; for (int marker = 0; marker < thisBlock.length; marker++){ thisBlock[marker] = ((Integer)goodies.elementAt(marker)).intValue(); } if (thisBlock.length > 1){ theBlocks.add(thisBlock); } } theData.guessBlocks(BLOX_CUSTOM, theBlocks); } if (tdtPanel != null){ tdtPanel.refreshTable(); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } if (hapDisplay != null && theData.blocksChanged){ setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } hapScroller.setViewportView(hapDisplay); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); theData.blocksChanged = false; } }
1,109,729
public void doAssociationTests(Vector affStatus, Vector permuteInd, Vector kidAffStatus) { if(fullProbMap == null || superdata == null || realAffectedStatus == null) { return; } if(affStatus == null){ affStatus = realAffectedStatus; } if(permuteInd == null) { permuteInd = new Vector(); for (int i = 0; i < superdata.length; i++){ permuteInd.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); 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); 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; } 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 kidAffStatus) { if(fullProbMap == null || superdata == null || realAffectedStatus == null || realKidAffectedStatus == null) { return; } if(affStatus == null){ affStatus = realAffectedStatus; } if(permuteInd == null) { permuteInd = new Vector(); for (int i = 0; i < superdata.length; i++){ permuteInd.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); 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); 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; } 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,732
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; } output.startElement(namespace, localName, name, attributes); getBody().run(context, output); output.endElement(namespace, localName, name); }
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; } output.startElement(namespace, localName, name, attributes); invokeBody( output); output.endElement(namespace, localName, name); }
1,109,735
public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_APPROVE; setVisible( false ); }
public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_APPROVE; setVisible( false ); }
1,109,737
public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_CANCEL; setVisible( false ); }
public void actionPerformed( ActionEvent e ) { returnReason = RETURN_REASON_APPROVE; setVisible( false ); }
1,109,738
public static void main(String[] args) throws Exception { UserManager userManager = UserManager.getInstance(); User user = null; char[] password = null; int invalidAttempts = 0; do{ if(invalidAttempts > 0){ System.out.println("Invalid Admin Password."); } /* get the password */ password = PasswordField.getPassword("Enter password:"); /* the password should match for the admin user */ user = userManager.verifyUsernamePassword(AuthConstants.USER_ADMIN, password); invalidAttempts ++; if(invalidAttempts >= 3){ break; } }while(user == null); /* exit if the admin password is still invalid */ if(user == null){ System.out.println("Number of invalid attempts exceeded. Exiting !"); return; } /* initialize ServiceFactory */ ServiceFactory.init(ServiceFactory.MODE_LOCAL); /* initialize crypto */ Crypto.init(password); /* clear the password */ Arrays.fill(password, ' '); /* load ACLs */ ACLStore.init(); /* start the application */ start(); }
public static void main(String[] args) throws Exception { UserManager userManager = UserManager.getInstance(); User user = null; char[] password = null; int invalidAttempts = 0; if(args.length == 1){ password = args[0].toCharArray(); user = userManager.verifyUsernamePassword( AuthConstants.USER_ADMIN, password); if(user == null){ invalidAttempts ++; } } while(user == null){ if(invalidAttempts > 0){ System.out.println("Invalid Admin Password."); } /* get the password */ password = PasswordField.getPassword("Enter password:"); /* the password should match for the admin user */ user = userManager.verifyUsernamePassword(AuthConstants.USER_ADMIN, password); invalidAttempts ++; if(invalidAttempts >= 3){ break; } }while(user == null); /* exit if the admin password is still invalid */ if(user == null){ System.out.println("Number of invalid attempts exceeded. Exiting !"); return; } /* initialize ServiceFactory */ ServiceFactory.init(ServiceFactory.MODE_LOCAL); /* initialize crypto */ Crypto.init(password); /* clear the password */ Arrays.fill(password, ' '); /* load ACLs */ ACLStore.init(); /* start the application */ start(); }
1,109,740
public static void main(String[] args) throws Exception { UserManager userManager = UserManager.getInstance(); User user = null; char[] password = null; int invalidAttempts = 0; do{ if(invalidAttempts > 0){ System.out.println("Invalid Admin Password."); } /* get the password */ password = PasswordField.getPassword("Enter password:"); /* the password should match for the admin user */ user = userManager.verifyUsernamePassword(AuthConstants.USER_ADMIN, password); invalidAttempts ++; if(invalidAttempts >= 3){ break; } }while(user == null); /* exit if the admin password is still invalid */ if(user == null){ System.out.println("Number of invalid attempts exceeded. Exiting !"); return; } /* initialize ServiceFactory */ ServiceFactory.init(ServiceFactory.MODE_LOCAL); /* initialize crypto */ Crypto.init(password); /* clear the password */ Arrays.fill(password, ' '); /* load ACLs */ ACLStore.init(); /* start the application */ start(); }
public static void main(String[] args) throws Exception { UserManager userManager = UserManager.getInstance(); User user = null; char[] password = null; int invalidAttempts = 0; do{ if(invalidAttempts > 0){ System.out.println("Invalid Admin Password."); } /* get the password */ password = PasswordField.getPassword("Enter password:"); /* the password should match for the admin user */ user = userManager.verifyUsernamePassword(AuthConstants.USER_ADMIN, password); invalidAttempts ++; if(invalidAttempts >= 3){ break; } } /* exit if the admin password is still invalid */ if(user == null){ System.out.println("Number of invalid attempts exceeded. Exiting !"); return; } /* initialize ServiceFactory */ ServiceFactory.init(ServiceFactory.MODE_LOCAL); /* initialize crypto */ Crypto.init(password); /* clear the password */ Arrays.fill(password, ' '); /* load ACLs */ ACLStore.init(); /* start the application */ start(); }
1,109,741
public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { int clickX = e.getX(); int clickY = e.getY(); if (showWM && wmInteriorRect.contains(clickX,clickY)){ //convert a click on the worldmap to a point on the big picture int bigClickX = (((clickX - getVisibleRect().x - (worldmap.getWidth()-wmInteriorRect.width)/2) * chartSize.width) / wmInteriorRect.width)-getVisibleRect().width/2; int bigClickY = (((clickY - getVisibleRect().y - (worldmap.getHeight() - wmInteriorRect.height)/2 - (getVisibleRect().height-worldmap.getHeight())) * chartSize.height) / wmInteriorRect.height) - getVisibleRect().height/2 + infoHeight; //System.out.println(chartSize.height); //if the clicks are near the edges, correct values if (bigClickX > chartSize.width - getVisibleRect().width){ bigClickX = chartSize.width - getVisibleRect().width; } if (bigClickX < 0){ bigClickX = 0; } if (bigClickY > chartSize.height - getVisibleRect().height + infoHeight){ bigClickY = chartSize.height - getVisibleRect().height + infoHeight; } if (bigClickY < 0){ bigClickY = 0; } ((JViewport)getParent()).setViewPosition(new Point(bigClickX,bigClickY)); }else{ theHV.changeBlocks(BLOX_CUSTOM); Rectangle2D blockselector = new Rectangle2D.Double(clickXShift-boxRadius,clickYShift - boxRadius, alignedPositions[alignedPositions.length-1], boxSize); if(blockselector.contains(clickX,clickY)){ int whichMarker = getPreciseMarkerAt(clickX - clickXShift); if (whichMarker > -1){ if (theData.isInBlock[whichMarker]){ theData.removeFromBlock(whichMarker); repaint(); } else if (whichMarker > 0 && whichMarker < Chromosome.realIndex.length){ theData.addMarkerIntoSurroundingBlock(whichMarker); } } } } } }
public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { int clickX = e.getX(); int clickY = e.getY(); if (showWM && wmInteriorRect.contains(clickX,clickY)){ //convert a click on the worldmap to a point on the big picture int bigClickX = (((clickX - getVisibleRect().x - (worldmap.getWidth()-wmInteriorRect.width)/2) * chartSize.width) / wmInteriorRect.width)-getVisibleRect().width/2; int bigClickY = (((clickY - getVisibleRect().y - (worldmap.getHeight() - wmInteriorRect.height)/2 - (getVisibleRect().height-worldmap.getHeight())) * chartSize.height) / wmInteriorRect.height) - getVisibleRect().height/2; //System.out.println(chartSize.height); //if the clicks are near the edges, correct values if (bigClickX > chartSize.width - getVisibleRect().width){ bigClickX = chartSize.width - getVisibleRect().width; } if (bigClickX < 0){ bigClickX = 0; } if (bigClickY > chartSize.height - getVisibleRect().height + infoHeight){ bigClickY = chartSize.height - getVisibleRect().height + infoHeight; } if (bigClickY < 0){ bigClickY = 0; } ((JViewport)getParent()).setViewPosition(new Point(bigClickX,bigClickY)); }else{ theHV.changeBlocks(BLOX_CUSTOM); Rectangle2D blockselector = new Rectangle2D.Double(clickXShift-boxRadius,clickYShift - boxRadius, alignedPositions[alignedPositions.length-1], boxSize); if(blockselector.contains(clickX,clickY)){ int whichMarker = getPreciseMarkerAt(clickX - clickXShift); if (whichMarker > -1){ if (theData.isInBlock[whichMarker]){ theData.removeFromBlock(whichMarker); repaint(); } else if (whichMarker > 0 && whichMarker < Chromosome.realIndex.length){ theData.addMarkerIntoSurroundingBlock(whichMarker); } } } } } }
1,109,743
public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { int clickX = e.getX(); int clickY = e.getY(); if (showWM && wmInteriorRect.contains(clickX,clickY)){ //convert a click on the worldmap to a point on the big picture int bigClickX = (((clickX - getVisibleRect().x - (worldmap.getWidth()-wmInteriorRect.width)/2) * chartSize.width) / wmInteriorRect.width)-getVisibleRect().width/2; int bigClickY = (((clickY - getVisibleRect().y - (worldmap.getHeight() - wmInteriorRect.height)/2 - (getVisibleRect().height-worldmap.getHeight())) * chartSize.height) / wmInteriorRect.height) - getVisibleRect().height/2 + infoHeight; //System.out.println(chartSize.height); //if the clicks are near the edges, correct values if (bigClickX > chartSize.width - getVisibleRect().width){ bigClickX = chartSize.width - getVisibleRect().width; } if (bigClickX < 0){ bigClickX = 0; } if (bigClickY > chartSize.height - getVisibleRect().height + infoHeight){ bigClickY = chartSize.height - getVisibleRect().height + infoHeight; } if (bigClickY < 0){ bigClickY = 0; } ((JViewport)getParent()).setViewPosition(new Point(bigClickX,bigClickY)); }else{ theHV.changeBlocks(BLOX_CUSTOM); Rectangle2D blockselector = new Rectangle2D.Double(clickXShift-boxRadius,clickYShift - boxRadius, alignedPositions[alignedPositions.length-1], boxSize); if(blockselector.contains(clickX,clickY)){ int whichMarker = getPreciseMarkerAt(clickX - clickXShift); if (whichMarker > -1){ if (theData.isInBlock[whichMarker]){ theData.removeFromBlock(whichMarker); repaint(); } else if (whichMarker > 0 && whichMarker < Chromosome.realIndex.length){ theData.addMarkerIntoSurroundingBlock(whichMarker); } } } } } }
public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { int clickX = e.getX(); int clickY = e.getY(); if (showWM && wmInteriorRect.contains(clickX,clickY)){ //convert a click on the worldmap to a point on the big picture int bigClickX = (((clickX - getVisibleRect().x - (worldmap.getWidth()-wmInteriorRect.width)/2) * chartSize.width) / wmInteriorRect.width)-getVisibleRect().width/2; int bigClickY = (((clickY - getVisibleRect().y - (worldmap.getHeight() - wmInteriorRect.height)/2 - (getVisibleRect().height-worldmap.getHeight())) * chartSize.height) / wmInteriorRect.height) - getVisibleRect().height/2 + infoHeight; //System.out.println(chartSize.height); //if the clicks are near the edges, correct values if (bigClickX > chartSize.width - getVisibleRect().width){ bigClickX = chartSize.width - getVisibleRect().width; } if (bigClickX < 0){ bigClickX = 0; } if (bigClickY > chartSize.height - getVisibleRect().height + infoHeight){ bigClickY = chartSize.height - getVisibleRect().height + infoHeight; } if (bigClickY < 0){ bigClickY = 0; } ((JViewport)getParent()).setViewPosition(new Point(bigClickX,bigClickY)); }else{ theHV.changeBlocks(BLOX_CUSTOM); Rectangle2D blockselector = new Rectangle2D.Double(clickXShift-boxRadius,clickYShift - boxRadius, alignedPositions[alignedPositions.length-1], boxSize); if(blockselector.contains(clickX,clickY)){ int whichMarker = getPreciseMarkerAt(clickX - clickXShift); if (whichMarker > -1){ if (theData.isInBlock[whichMarker]){ theData.removeFromBlock(whichMarker); repaint(); } else if (whichMarker > 0 && whichMarker < Chromosome.realIndex.length){ theData.addMarkerIntoSurroundingBlock(whichMarker); } } } } } }
1,109,744
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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 < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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 < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
1,109,745
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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 < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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))); 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 < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
1,109,746
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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 < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
1,109,747
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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 < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() == 0){ //if there are no valid markers return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage, H_BORDER,V_BORDER,this); // not sure if this is an imageObserver, however imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); //see if the user has right-clicked to popup some marker info if(popupExists){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } if (showWM && !forExport){ //dataset is big enough to require worldmap 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 < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x])/(scalefactor*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.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if we're drawing a worldmap resize rect if (resizeRectExists){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRectExists){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
1,109,748
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } }
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice; if (info[5].equals("I+II")){ phaseChoice = "II"; }else{ phaseChoice = info[5]; } boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } }
1,109,749
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } }
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { GZIPInputStream g = new GZIPInputStream(hmpCon.getInputStream()); BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(g)); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } }
1,109,750
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } }
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database: \n" + io.getMessage()); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database: \n" + io.getMessage()); } }
1,109,751
public CheckDataPanel(File file) throws IOException{ //okay, for now we're going to assume the ped file has no header Vector pedFileStrings = new Vector(); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while((line = reader.readLine())!=null){ pedFileStrings.add(line); } pedfile = new PedFile(); pedfile.parse(pedFileStrings); //Vector result = data.check(); Vector result = pedfile.check(); int numResults = result.size(); Vector tableColumnNames = new Vector(); tableColumnNames.add("Name"); tableColumnNames.add("ObsHET"); tableColumnNames.add("PredHET"); tableColumnNames.add("HWpval"); tableColumnNames.add("%Geno"); tableColumnNames.add("FamTrio"); tableColumnNames.add("MendErr"); tableColumnNames.add("Rating"); Vector tableData = new Vector(); int[] ratingArray = new int[numResults]; for (int i = 0; i < numResults; i++){ Vector tempVect = new Vector(); MarkerResult currentResult = (MarkerResult)result.get(i); tempVect.add(currentResult.getName()); tempVect.add(new Double(currentResult.getObsHet())); tempVect.add(new Double(currentResult.getPredHet())); tempVect.add(new Double(currentResult.getHWpvalue())); tempVect.add(new Double(currentResult.getGenoPercent())); tempVect.add(new Integer(currentResult.getFamTrioNum())); tempVect.add(new Integer(currentResult.getMendErrNum())); if (currentResult.getRating() > 0){ tempVect.add(new Boolean(true)); }else{ tempVect.add(new Boolean(false)); } //this value is never displayed, just kept for bookkeeping ratingArray[i] = currentResult.getRating(); tableData.add(tempVect.clone()); } final CheckDataTableModel tableModel = new CheckDataTableModel(tableColumnNames, tableData, ratingArray); tableModel.addTableModelListener(this); table = new JTable(tableModel); final CheckDataCellRenderer renderer = new CheckDataCellRenderer(); try{ table.setDefaultRenderer(Class.forName("java.lang.Double"), renderer); table.setDefaultRenderer(Class.forName("java.lang.Integer"), renderer); }catch (Exception e){ } table.getColumnModel().getColumn(0).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); }
public CheckDataPanel(File file) throws IOException{ //okay, for now we're going to assume the ped file has no header Vector pedFileStrings = new Vector(); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while((line = reader.readLine())!=null){ pedFileStrings.add(line); } pedfile = new PedFile(); pedfile.parse(pedFileStrings); //Vector result = data.check(); Vector result = pedfile.check(); int numResults = result.size(); Vector tableColumnNames = new Vector(); tableColumnNames.add("Name"); tableColumnNames.add("ObsHET"); tableColumnNames.add("PredHET"); tableColumnNames.add("HWpval"); tableColumnNames.add("%Geno"); tableColumnNames.add("FamTrio"); tableColumnNames.add("MendErr"); tableColumnNames.add("Rating"); Vector tableData = new Vector(); int[] ratingArray = new int[numResults]; for (int i = 0; i < numResults; i++){ Vector tempVect = new Vector(); MarkerResult currentResult = (MarkerResult)result.get(i); tempVect.add(currentResult.getName()); tempVect.add(new Double(currentResult.getObsHet())); tempVect.add(new Double(currentResult.getPredHet())); tempVect.add(new Double(currentResult.getHWpvalue())); tempVect.add(new Double(currentResult.getGenoPercent())); tempVect.add(new Integer(currentResult.getFamTrioNum())); tempVect.add(new Integer(currentResult.getMendErrNum())); if (currentResult.getRating() > 0){ tempVect.add(new Boolean(true)); }else{ tempVect.add(new Boolean(false)); } //this value is never displayed, just kept for bookkeeping ratingArray[i] = currentResult.getRating(); tableData.add(tempVect.clone()); } final CheckDataTableModel tableModel = new CheckDataTableModel(tableColumnNames, tableData, ratingArray); tableModel.addTableModelListener(this); table = new JTable(tableModel); final CheckDataCellRenderer renderer = new CheckDataCellRenderer(); try{ table.setDefaultRenderer(Class.forName("java.lang.Double"), renderer); table.setDefaultRenderer(Class.forName("java.lang.Integer"), renderer); }catch (Exception e){ } table.getColumnModel().getColumn(0).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); }
1,109,752
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1)); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } }
public void parsePhasedDownload(String[] info) throws IOException, PedFileException{ String targetChrom = "chr" + info[4]; Chromosome.setDataChrom(targetChrom); Chromosome.setDataBuild("ncbi_b35"); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Vector hmpVector = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); String populationChoice; if (info[1].equals("CHB+JPT")){ populationChoice = "JC"; }else{ populationChoice = info[1]; } boolean pseudoChecked = false; long startPos; if (info[2].equals("0")){ startPos = 1; }else{ startPos = (Integer.parseInt(info[2]))*1000; } long stopPos = (Integer.parseInt(info[3]))*1000; String phaseChoice = info[5]; boolean infoDone = false; boolean hminfoDone = false; String urlHmp = "http://www.hapmap.org/cgi-perl/phased?chr=" + targetChrom + "&pop=" + populationChoice + "&start=" + startPos + "&stop=" + stopPos + "&ds=p" + phaseChoice + "&out=txt&filter=cons+" + populationChoice.toLowerCase(); try{ URL hmpUrl = new URL(urlHmp); HttpURLConnection hmpCon = (HttpURLConnection)hmpUrl.openConnection(); hmpCon.connect(); int response = hmpCon.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw new IOException("Could not connect to HapMap database."); }else { BufferedReader hmpBuffReader = new BufferedReader(new InputStreamReader(hmpCon.getInputStream())); String hmpLine; char token; int columns; while((hmpLine = hmpBuffReader.readLine())!=null){ if (hmpLine.startsWith("---")){ //continue; }else if (hmpLine.startsWith("pop:")){ //continue; }else if (hmpLine.startsWith("build:")){ StringTokenizer buildSt = new StringTokenizer(hmpLine); buildSt.nextToken(); Chromosome.setDataBuild(new String(buildSt.nextToken())); }else if (hmpLine.startsWith("hapmap_release:")){ //continue; }else if (hmpLine.startsWith("filters:")){ //continue; }else if (hmpLine.startsWith("start:")){ //continue; }else if (hmpLine.startsWith("stop:")){ //continue; }else if (hmpLine.startsWith("snps:")){ //continue; }else if (hmpLine.startsWith("phased_haplotypes:")){ infoDone = true; }else if (hmpLine.startsWith("No")){ throw new PedFileException(hmpLine); }else if (hmpLine.startsWith("Too many")){ throw new PedFileException(hmpLine); }else if (!infoDone){ StringTokenizer posSt = new StringTokenizer(hmpLine," \t:-"); //posSt.nextToken(); //skip the - legendMarkers.add(posSt.nextToken()); legendPositions.add(posSt.nextToken()); }else if (infoDone){ if (!hminfoDone){ hminfo = new String[legendPositions.size()][2]; for (int i = 0; i < legendPositions.size(); i++){ //marker name. hminfo[i][0] = (String)legendMarkers.get(i); //marker position. hminfo[i][1] = (String)legendPositions.get(i); } hminfoDone = true; } hmpVector.add(hmpLine); } } for (int i = 0; i < hmpVector.size(); i++){ StringTokenizer dataSt = new StringTokenizer((String)hmpVector.get(i)); dataSt.nextToken(); //skip the - String newid = dataSt.nextToken(); //individual ID with _c1/_c2 String data = dataSt.nextToken(); //alleles columns = data.length(); StringTokenizer filter = new StringTokenizer(newid,"_:"); String id = filter.nextToken(); String strand = filter.nextToken(); if (strand.equals("c1")){ //Only set up a new individual on c1. ind = new Individual(columns, true); ind.setIndividualID(new String(id)); if (columns != legendMarkers.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); StringTokenizer dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); //skip individualID since we already have it. dt.nextToken(); ind.setDadID(dt.nextToken()); ind.setMomID(dt.nextToken()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + ind.getIndividualID()); } if (!pseudoChecked){ if (ind.getGender() == Individual.MALE){ pseudoChecked = true; if (Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ StringTokenizer checkSt = new StringTokenizer((String)hmpVector.get(i+1),":- \t"); String checkNewid = checkSt.nextToken(); checkSt.nextToken(); //alleles StringTokenizer checkFilter = new StringTokenizer(checkNewid,"_"); checkFilter.nextToken(); String checkStrand = checkFilter.nextToken(); if (checkStrand.equals("c2")){ Chromosome.setDataChrom("chrp"); } } } } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } int index = 0; if (strand.equals("c1")){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } for(int k = 0; k < columns; k++){ token = data.charAt(k); if (strand.equals("c1")){ if (token == 'A'){ byteDataT[index] = 1; }else if (token == 'C'){ byteDataT[index] = 2; }else if (token == 'G'){ byteDataT[index] = 3; }else if (token == 'T'){ byteDataT[index] = 4; }else { throw new PedFileException("Invalid Allele: " + token); } }else{ if (token == 'A'){ byteDataU[index] = 1; }else if (token == 'C'){ byteDataU[index] = 2; }else if (token == 'G'){ byteDataU[index] = 3; }else if (token == 'T'){ byteDataU[index] = 4; }else if (token == '-'){ /*if (!(Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ throw new PedFileException("Missing allele on non X-chromosome data"); }else{ byteDataU[index] = byteDataT[index]; }*/ throw new PedFileException("Haploview does not currently support regions encompassing both\n" + " pseudoautosomal and non-pseudoautosomal markers."); }else { throw new PedFileException("File format error."); } } index++; } if (strand.equals("c2")){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataU[j]); } }else if (strand.equals("c1") && (ind.getGender() == Individual.MALE) && (Chromosome.getDataChrom().equalsIgnoreCase("chrx"))){ for(int j=0; j < columns; j++){ ind.addMarker(byteDataT[j], byteDataT[j]); } } } } hmpCon.disconnect(); }catch(IOException io){ throw new IOException("Could not connect to HapMap database."); } }
1,109,753
public ApplicationConfigData addApplication(ServiceContext context, ApplicationConfigData data){ AccessController.checkAccess(context, ACLConstants.ACL_ADD_APPLICATIONS); /* do the operation */ String appId = ApplicationConfig.getNextApplicationId(); Integer port = data.getPort(); ApplicationConfig config = ApplicationConfigFactory.create(appId, data.getName(), data.getType(), data.getHost(), port, data.getURL(), data.getUsername(), data.getPassword(), data.getParamValues()); try { ApplicationConfigManager.addApplication(config); } catch (ApplicationConfigManager.DuplicateApplicationNameException e) { throw new ServiceException(ErrorCodes.APPLICATION_NAME_ALREADY_EXISTS, e.getAppName()); } data.setApplicationId(appId); /* log the operation */ UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Added application "+ "\""+config.getName()+"\""); return data; }
public ApplicationConfigData addApplication(ServiceContext context, ApplicationConfigData data){ AccessController.checkAccess(context, ACLConstants.ACL_ADD_APPLICATIONS); /* do the operation */ String appId = ApplicationConfig.getNextApplicationId(); Integer port = data.getPort(); ApplicationConfig config = ApplicationConfigFactory.create(appId, data.getName(), data.getType(), data.getHost(), port, data.getURL(), data.getUsername(), data.getPassword(), data.getParamValues()); try { ApplicationConfigManager.addApplication(config); } catch (ApplicationConfigManager.DuplicateApplicationNameException e) { throw new ServiceException(ErrorCodes.APPLICATION_NAME_ALREADY_EXISTS, e.getAppName()); } data.setApplicationId(appId); /* log the operation */ UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Added application "+ "\""+config.getName()+"\""); return data; }
1,109,754
public static void addDashboard(DashboardConfig config){ assert config != null; dashboardConfigs.add(config); saveConfig(); }
public static void addDashboard(DashboardConfig config){ assert config != null; dashboardConfigs.add(config); saveConfig(); }
1,109,755
public static DashboardConfig getDashboard(String dashboardId){ for(Iterator it=dashboardConfigs.iterator(); it.hasNext();){ DashboardConfig config = (DashboardConfig)it.next(); if(config.getDashboardId().equals(dashboardId)){ return config; } } return null; }
public static DashboardConfig getDashboard(String dashboardId){ for(Iterator it=dashboardConfigs.iterator(); it.hasNext();){ DashboardConfig config = (DashboardConfig)it.next(); if(config.getDashboardId().equals(dashboardId)){ return config; } } return null; }
1,109,756
public static void updateDashboard(DashboardConfig config){ assert config != null: "application config is null"; synchronized(writeLock){ int index = dashboardConfigs.indexOf(config); assert index != -1; dashboardConfigs.remove(index); dashboardConfigs.add(index, config); saveConfig(); } }
public static void updateDashboard(DashboardConfig config){ assert config != null: "application config is null"; synchronized(writeLock){ int index = dashboardConfigs.indexOf(config); assert index != -1; dashboardConfigs.remove(index); dashboardConfigs.add(index, config); saveConfig(); } }
1,109,757
public void showDbcsDialog() { final DBCSPanel dbcsPanel = new DBCSPanel(); dbcsPanel.setDbcs(db.getDataSource()); DBCS_OkAction okAction = new DBCS_OkAction(dbcsPanel, true); Action cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dbcsPanel.discardChanges(); } }; JDialog d = ArchitectPanelBuilder.createArchitectPanelDialog( dbcsPanel, ArchitectFrame.getMainInstance(), "Target Database Connection", ArchitectPanelBuilder.OK_BUTTON_LABEL, okAction, cancelAction); okAction.setConnectionDialog(d); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); dbcsDialog = d; dbcsDialog.setVisible(true); }
public void showDbcsDialog() { final DBCSPanel dbcsPanel = new DBCSPanel(); dbcsPanel.setDbcs(db.getDataSource()); Action cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dbcsPanel.discardChanges(); } }; JDialog d = ArchitectPanelBuilder.createArchitectPanelDialog( dbcsPanel, ArchitectFrame.getMainInstance(), "Target Database Connection", ArchitectPanelBuilder.OK_BUTTON_LABEL, okAction, cancelAction); okAction.setConnectionDialog(d); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); dbcsDialog = d; dbcsDialog.setVisible(true); }
1,109,758
public void doTag(XMLOutput output) throws Exception { try { conn = getConnection(); } catch (SQLException e) { throw new JellyException(sql + ": " + e.getMessage(), e); } /* * Use the SQL statement specified by the sql attribute, if any, * otherwise use the body as the statement. */ String sqlStatement = null; if (sql != null) { sqlStatement = sql; } else { sqlStatement = getBodyText(); } if (sqlStatement == null || sqlStatement.trim().length() == 0) { throw new JellyException(Resources.getMessage("SQL_NO_STATEMENT")); } Statement statement = null; int result = 0; try { if ( hasParameters() ) { PreparedStatement ps = conn.prepareStatement(sqlStatement); statement = ps; setParameters(ps); result = ps.executeUpdate(); } else { statement = conn.createStatement(); result = statement.executeUpdate(sqlStatement); } if (var != null) { context.setVariable(var, new Integer(result)); } } catch (SQLException e) { throw new JellyException(sqlStatement + ": " + e.getMessage(), e); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { } // Not much we can do } if (conn != null && !isPartOfTransaction) { try { conn.close(); } catch (SQLException e) { // Not much we can do } } clearParameters(); } }
public void doTag(XMLOutput output) throws Exception { try { conn = getConnection(); log.error("Caught exception while closing statement: " + e, e); } catch (SQLException e) { throw new JellyException(sql + ": " + e.getMessage(), e); log.error("Caught exception while closing statement: " + e, e); } /* * Use the SQL statement specified by the sql attribute, if any, * otherwise use the body as the statement. */ String sqlStatement = null; if (sql != null) { sqlStatement = sql; log.error("Caught exception while closing statement: " + e, e); } else { sqlStatement = getBodyText(); log.error("Caught exception while closing statement: " + e, e); } if (sqlStatement == null || sqlStatement.trim().length() == 0) { throw new JellyException(Resources.getMessage("SQL_NO_STATEMENT")); log.error("Caught exception while closing statement: " + e, e); } Statement statement = null; int result = 0; try { if ( hasParameters() ) { PreparedStatement ps = conn.prepareStatement(sqlStatement); statement = ps; setParameters(ps); result = ps.executeUpdate(); log.error("Caught exception while closing statement: " + e, e); } else { statement = conn.createStatement(); result = statement.executeUpdate(sqlStatement); log.error("Caught exception while closing statement: " + e, e); } if (var != null) { context.setVariable(var, new Integer(result)); log.error("Caught exception while closing statement: " + e, e); } log.error("Caught exception while closing statement: " + e, e); } catch (SQLException e) { throw new JellyException(sqlStatement + ": " + e.getMessage(), e); log.error("Caught exception while closing statement: " + e, e); } finally { if (statement != null) { try { statement.close(); log.error("Caught exception while closing statement: " + e, e); } catch (SQLException e) { log.error("Caught exception while closing statement: " + e, e); } // Not much we can do log.error("Caught exception while closing statement: " + e, e); } if (conn != null && !isPartOfTransaction) { try { conn.close(); log.error("Caught exception while closing statement: " + e, e); } catch (SQLException e) { // Not much we can do log.error("Caught exception while closing statement: " + e, e); } log.error("Caught exception while closing statement: " + e, e); } clearParameters(); log.error("Caught exception while closing statement: " + e, e); } log.error("Caught exception while closing statement: " + e, e); }
1,109,759
public ObjectName getObjectName() { try { final String objectNameString = request.getParameter(RequestParams.OBJECT_NAME); if(objectNameString != null){ return new ObjectName(objectNameString); }else{ return null; } } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } }
public ObjectName getObjectName() { try { final String objectNameString = request.getParameter(RequestParams.OBJECT_NAME); if(objectNameString != null){ return new ObjectName(objectNameString); }else{ return null; } } catch (MalformedObjectNameException e) { throw new RuntimeException(e); } }
1,109,762
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { ApplicationForm appForm = (ApplicationForm)actionForm; /* create ApplicationConfigData from this form */ ApplicationConfigData appConfigData = new ApplicationConfigData(); Utils.copyProperties(appConfigData, appForm); ConfigurationService service = ServiceFactory.getConfigurationService(); service.addApplication(Utils.getServiceContext(context), appConfigData); return mapping.findForward(Forwards.SUCCESS); }
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { ApplicationForm appForm = (ApplicationForm)actionForm; /* create ApplicationConfigData from this form */ ApplicationConfigData appConfigData = new ApplicationConfigData(); CoreUtils.copyProperties(appConfigData, appForm); ConfigurationService service = ServiceFactory.getConfigurationService(); service.addApplication(Utils.getServiceContext(context), appConfigData); return mapping.findForward(Forwards.SUCCESS); }
1,109,763
public HaploAssocPanel(Haplotype[][] haps){ initialHaplotypeDisplayThreshold = Options.getHaplotypeDisplayThreshold(); Vector colNames = new Vector(); colNames.add("Haplotype"); colNames.add("Freq."); if (Options.getAssocTest() == ASSOC_TRIO){ colNames.add("T:U"); }else{ colNames.add("Case, Control Ratios"); } colNames.add("Chi Squared"); colNames.add("p value"); HaplotypeAssociationNode root = new HaplotypeAssociationNode("Haplotype Associations"); String[] alleleCodes = new String[5]; alleleCodes[0] = "X"; alleleCodes[1] = "A"; alleleCodes[2] = "C"; alleleCodes[3] = "G"; alleleCodes[4] = "T"; for(int i=0;i< haps.length;i++){ Haplotype[] curBlock = haps[i]; HaplotypeAssociationNode han = new HaplotypeAssociationNode("Block " + (i+1)); double chisq; for(int j=0;j< curBlock.length; j++) { if (curBlock[j].getPercentage()*100 >= Options.getHaplotypeDisplayThreshold()){ int[] genotypes = curBlock[j].getGeno(); StringBuffer curHap = new StringBuffer(genotypes.length); for(int k=0;k<genotypes.length;k++) { curHap.append(alleleCodes[genotypes[k]]); } double[][] counts; if(Options.getAssocTest() == ASSOC_TRIO) { counts = new double[1][2]; counts[0][0] = curBlock[j].getTransCount(); counts[0][1] = curBlock[j].getUntransCount(); } else { counts = new double[2][2]; counts[0][0] = curBlock[j].getCaseFreq(); counts[1][0] = curBlock[j].getControlFreq(); double caseSum=0; double controlSum=0; for (int k=0; k < curBlock.length; k++){ if (j!=k){ caseSum += curBlock[k].getCaseFreq(); controlSum += curBlock[k].getControlFreq(); } } counts[0][1] = caseSum; counts[1][1] = controlSum; } chisq = getChiSq(counts); han.add(new HaplotypeAssociationNode(curHap.toString(),curBlock[j].getPercentage(),counts,chisq,getPValue(chisq))); } } root.add(han); } JTreeTable jtt = new JTreeTable(new HaplotypeAssociationModel(colNames, root)); jtt.getColumnModel().getColumn(0).setPreferredWidth(200); jtt.getColumnModel().getColumn(1).setPreferredWidth(50); jtt.getColumnModel().getColumn(2).setPreferredWidth(100); jtt.getColumnModel().getColumn(3).setPreferredWidth(100); jtt.getColumnModel().getColumn(4).setPreferredWidth(100); jtt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Font monoFont = new Font("Monospaced",Font.PLAIN,12); jtt.setFont(monoFont); JTree theTree = jtt.getTree(); theTree.setFont(monoFont); DefaultTreeCellRenderer r = new DefaultTreeCellRenderer(); r.setLeafIcon(null); r.setOpenIcon(null); r.setClosedIcon(null); theTree.setCellRenderer(r); jtt.setPreferredScrollableViewportSize(new Dimension(550,jtt.getPreferredScrollableViewportSize().height)); JScrollPane treeScroller = new JScrollPane(jtt); add(treeScroller); }
public HaploAssocPanel(Haplotype[][] haps){ initialHaplotypeDisplayThreshold = Options.getHaplotypeDisplayThreshold(); Vector colNames = new Vector(); colNames.add("Haplotype"); colNames.add("Freq."); if (Options.getAssocTest() == ASSOC_TRIO){ colNames.add("T:U"); }else{ colNames.add("Case, Control Ratios"); } colNames.add("Chi Squared"); colNames.add("p value"); HaplotypeAssociationNode root = new HaplotypeAssociationNode("Haplotype Associations"); String[] alleleCodes = new String[5]; alleleCodes[0] = "X"; alleleCodes[1] = "A"; alleleCodes[2] = "C"; alleleCodes[3] = "G"; alleleCodes[4] = "T"; for(int i=0;i< haps.length;i++){ Haplotype[] curBlock = haps[i]; HaplotypeAssociationNode han = new HaplotypeAssociationNode("Block " + (i+1)); double chisq; for(int j=0;j< curBlock.length; j++) { if (curBlock[j].getPercentage()*100 >= Options.getHaplotypeDisplayThreshold()){ int[] genotypes = curBlock[j].getGeno(); StringBuffer curHap = new StringBuffer(genotypes.length); for(int k=0;k<genotypes.length;k++) { curHap.append(alleleCodes[genotypes[k]]); } double[][] counts; if(Options.getAssocTest() == ASSOC_TRIO) { counts = new double[1][2]; counts[0][0] = curBlock[j].getTransCount(); counts[0][1] = curBlock[j].getUntransCount(); } else { counts = new double[2][2]; counts[0][0] = curBlock[j].getCaseFreq(); counts[1][0] = curBlock[j].getControlFreq(); double caseSum=0; double controlSum=0; for (int k=0; k < curBlock.length; k++){ if (j!=k){ caseSum += curBlock[k].getCaseFreq(); controlSum += curBlock[k].getControlFreq(); } } counts[0][1] = caseSum; counts[1][1] = controlSum; } chisq = getChiSq(counts); han.add(new HaplotypeAssociationNode(curHap.toString(),curBlock[j].getPercentage(),counts,chisq,getPValue(chisq))); } } root.add(han); } JTreeTable jtt = new JTreeTable(new HaplotypeAssociationModel(colNames, root)); jtt.getColumnModel().getColumn(0).setPreferredWidth(200); jtt.getColumnModel().getColumn(1).setPreferredWidth(50); jtt.getColumnModel().getColumn(2).setPreferredWidth(100); jtt.getColumnModel().getColumn(3).setPreferredWidth(100); jtt.getColumnModel().getColumn(4).setPreferredWidth(100); jtt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Font monoFont = new Font("Monospaced",Font.PLAIN,12); jtt.setFont(monoFont); JTree theTree = jtt.getTree(); theTree.setFont(monoFont); DefaultTreeCellRenderer r = new DefaultTreeCellRenderer(); r.setLeafIcon(null); r.setOpenIcon(null); r.setClosedIcon(null); theTree.setCellRenderer(r); jtt.setPreferredScrollableViewportSize(new Dimension(550,jtt.getPreferredScrollableViewportSize().height)); JScrollPane treeScroller = new JScrollPane(jtt); add(treeScroller); }
1,109,764
public BufferedImage export(int start, int stop, boolean compress) throws HaploViewException { forExport = true; exportStart = -1; if (start < 0){ start = 0; } while (true){ //if the marker we want has been filtered walk up until we find a valid one exportStart = Chromosome.filterIndex[start]; if (exportStart == -1){ start++; if (start >= Chromosome.getUnfilteredSize()){ forExport = false; throw new HaploViewException("Invalid marker range for export."); } }else{ break; } } exportStop = -1; if (stop >= Chromosome.getUnfilteredSize()){ stop = Chromosome.getUnfilteredSize()-1; } while (true){ //if the marker we want has been filtered walk down until we find a valid one exportStop = Chromosome.filterIndex[stop-1]; if (exportStop == -1){ stop--; if (stop < 0){ forExport = false; throw new HaploViewException("Invalid marker range for export."); } }else{ break; } } this.computePreferredSize(); int startBS = boxSize; int startBR = boxRadius; boolean startPD = printDPrimeValues; boolean startMN = printMarkerNames; int startZL = zoomLevel; if (compress){ zoomLevel = 2; printDPrimeValues = false; printMarkerNames = false; if (boxSize > (1200/(stop - start))){ boxSize = 1200/(stop - start); if (boxSize < 2){ boxSize = 2; } //to make picture not look dumb we need to avoid odd numbers for really teeny boxes if (boxSize < 10){ if (boxSize%2 != 0){ boxSize++; } } boxRadius = boxSize/2; } this.computePreferredSize(); } Dimension pref = getPreferredSize(); if(pref.width > 10000 || pref.height > 10000) { throw new HaploViewException("Image too large. Try saving as compressed PNG."); } BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); boxSize = startBS; boxRadius = startBR; zoomLevel = startZL; printMarkerNames = startMN; printDPrimeValues = startPD; forExport = false; this.computePreferredSize(); return i; }
public BufferedImage export(int start, int stop, boolean compress) throws HaploViewException { forExport = true; exportStart = -1; if (start < 0){ start = 0; } while (true){ //if the marker we want has been filtered walk up until we find a valid one exportStart = Chromosome.filterIndex[start]; if (exportStart == -1){ start++; if (start >= Chromosome.getUnfilteredSize()){ forExport = false; throw new HaploViewException("Invalid marker range for export."); } }else{ break; } } exportStop = -1; if (stop >= Chromosome.getUnfilteredSize()){ stop = Chromosome.getUnfilteredSize()-1; } while (true){ //if the marker we want has been filtered walk down until we find a valid one exportStop = Chromosome.filterIndex[stop-1]; if (exportStop == -1){ stop--; if (stop < 0){ forExport = false; throw new HaploViewException("Invalid marker range for export."); } }else{ break; } } this.computePreferredSize(); int startBS = boxSize; int startBR = boxRadius; boolean startPD = printDPrimeValues; boolean startMN = printMarkerNames; int startZL = zoomLevel; if (compress){ zoomLevel = 2; printDPrimeValues = false; printMarkerNames = false; if (boxSize > (1200/(stop - start))){ boxSize = 1200/(stop - start); if (boxSize < 2){ boxSize = 2; } //to make picture not look dumb we need to avoid odd numbers for really teeny boxes if (boxSize < 10){ if (boxSize%2 != 0){ boxSize++; } } boxRadius = boxSize/2; } this.computePreferredSize(); } Dimension pref = getPreferredSize(); if(pref.width > 10000 || pref.height > 10000) { throw new HaploViewException("Image too large. Try saving as compressed PNG."); } BufferedImage i = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); boxSize = startBS; boxRadius = startBR; zoomLevel = startZL; printMarkerNames = startMN; printDPrimeValues = startPD; forExport = false; this.computePreferredSize(); return i; }
1,109,765
private int drawSourceTargetCluster(Graphics2D g, Map<SQLTable, TablePane> panes, int maxSourceWidth, int maxTargetWidth, int sy, SQLTable st, Collection<SQLTable> targets) { int sx = 0; int tx = maxSourceWidth + sourceTargetGap; int ty = sy; for (SQLTable targetTable : targets) { TablePane ttp = panes.get(targetTable); Dimension tpsize = ttp.getPreferredSize(); ttp.setBounds( tx + maxTargetWidth/2 - tpsize.width/2, ty, tpsize.width, tpsize.height); if (g != null && g.hitClip(ttp.getX(),ttp.getY(),ttp.getWidth(),ttp.getHeight())) { g.translate(ttp.getX(), ttp.getY()); ttp.paint(g); g.translate(-ttp.getX(), -ttp.getY()); } ty += ttp.getHeight(); } int targetsHeight = ty - sy; TablePane stp = panes.get(st); if (stp != null) { Dimension stpsize = stp.getPreferredSize(); stp.setBounds( sx + maxSourceWidth/2 - stpsize.width/2, Math.max(sy, sy + targetsHeight/2 - stpsize.height/2), stpsize.width, stpsize.height); if (g != null ) { if (g.hitClip(stp.getX(),stp.getY(),stp.getWidth(),stp.getHeight())) { g.translate(stp.getX(), stp.getY()); stp.paint(g); g.translate(-stp.getX(), -stp.getY()); } for (SQLTable targetTable : targets) { drawArrow(g, stp.getBounds(), panes.get(targetTable).getBounds()); } } } ty += unrelatedSourcesGap ; sy = Math.max(ty,sy+stp.getHeight()+unrelatedSourcesGap); return sy; }
private int drawSourceTargetCluster(Graphics2D g, Map<SQLTable, TablePane> panes, int maxSourceWidth, int maxTargetWidth, int sy, SQLTable st, Collection<SQLTable> targets) { int sx = 0; int tx = maxSourceWidth + sourceTargetGap; int ty = sy; for (SQLTable targetTable : targets) { TablePane ttp = panes.get(targetTable); Dimension tpsize = ttp.getPreferredSize(); ttp.setBounds( tx + maxTargetWidth/2 - tpsize.width/2, ty, tpsize.width, tpsize.height); if (g != null && g.hitClip(ttp.getX(),ttp.getY(),ttp.getWidth(),ttp.getHeight())) { g.translate(ttp.getX(), ttp.getY()); ttp.paint(g); g.translate(-ttp.getX(), -ttp.getY()); } ty += ttp.getHeight()+unrelatedSourcesGap; } int targetsHeight = ty - sy; TablePane stp = panes.get(st); if (stp != null) { Dimension stpsize = stp.getPreferredSize(); stp.setBounds( sx + maxSourceWidth/2 - stpsize.width/2, Math.max(sy, sy + targetsHeight/2 - stpsize.height/2), stpsize.width, stpsize.height); if (g != null ) { if (g.hitClip(stp.getX(),stp.getY(),stp.getWidth(),stp.getHeight())) { g.translate(stp.getX(), stp.getY()); stp.paint(g); g.translate(-stp.getX(), -stp.getY()); } for (SQLTable targetTable : targets) { drawArrow(g, stp.getBounds(), panes.get(targetTable).getBounds()); } } } ty += unrelatedSourcesGap ; sy = Math.max(ty,sy+stp.getHeight()+unrelatedSourcesGap); return sy; }
1,109,766
private int drawSourceTargetCluster(Graphics2D g, Map<SQLTable, TablePane> panes, int maxSourceWidth, int maxTargetWidth, int sy, SQLTable st, Collection<SQLTable> targets) { int sx = 0; int tx = maxSourceWidth + sourceTargetGap; int ty = sy; for (SQLTable targetTable : targets) { TablePane ttp = panes.get(targetTable); Dimension tpsize = ttp.getPreferredSize(); ttp.setBounds( tx + maxTargetWidth/2 - tpsize.width/2, ty, tpsize.width, tpsize.height); if (g != null && g.hitClip(ttp.getX(),ttp.getY(),ttp.getWidth(),ttp.getHeight())) { g.translate(ttp.getX(), ttp.getY()); ttp.paint(g); g.translate(-ttp.getX(), -ttp.getY()); } ty += ttp.getHeight(); } int targetsHeight = ty - sy; TablePane stp = panes.get(st); if (stp != null) { Dimension stpsize = stp.getPreferredSize(); stp.setBounds( sx + maxSourceWidth/2 - stpsize.width/2, Math.max(sy, sy + targetsHeight/2 - stpsize.height/2), stpsize.width, stpsize.height); if (g != null ) { if (g.hitClip(stp.getX(),stp.getY(),stp.getWidth(),stp.getHeight())) { g.translate(stp.getX(), stp.getY()); stp.paint(g); g.translate(-stp.getX(), -stp.getY()); } for (SQLTable targetTable : targets) { drawArrow(g, stp.getBounds(), panes.get(targetTable).getBounds()); } } } ty += unrelatedSourcesGap ; sy = Math.max(ty,sy+stp.getHeight()+unrelatedSourcesGap); return sy; }
private int drawSourceTargetCluster(Graphics2D g, Map<SQLTable, TablePane> panes, int maxSourceWidth, int maxTargetWidth, int sy, SQLTable st, Collection<SQLTable> targets) { int sx = 0; int tx = maxSourceWidth + sourceTargetGap; int ty = sy; for (SQLTable targetTable : targets) { TablePane ttp = panes.get(targetTable); Dimension tpsize = ttp.getPreferredSize(); ttp.setBounds( tx + maxTargetWidth/2 - tpsize.width/2, ty, tpsize.width, tpsize.height); if (g != null && g.hitClip(ttp.getX(),ttp.getY(),ttp.getWidth(),ttp.getHeight())) { g.translate(ttp.getX(), ttp.getY()); ttp.paint(g); g.translate(-ttp.getX(), -ttp.getY()); } ty += ttp.getHeight(); } int targetsHeight = ty - sy; TablePane stp = panes.get(st); if (stp != null) { Dimension stpsize = stp.getPreferredSize(); stp.setBounds( sx + maxSourceWidth/2 - stpsize.width/2, Math.max(sy, sy + targetsHeight/2 - stpsize.height/2), stpsize.width, stpsize.height); if (g != null ) { if (g.hitClip(stp.getX(),stp.getY(),stp.getWidth(),stp.getHeight())) { g.translate(stp.getX(), stp.getY()); stp.paint(g); g.translate(-stp.getX(), -stp.getY()); } for (SQLTable targetTable : targets) { drawArrow(g, stp.getBounds(), panes.get(targetTable).getBounds()); } } } ty += unrelatedSourcesGap ; sy = Math.max(ty,sy+stp.getHeight()+unrelatedSourcesGap); return sy; }
1,109,767
public void fitToRect( double width, double height ) { // System.err.println( "Fitting to " + width + ", " + height ); fitSize = true; maxWidth = width; maxHeight = height; // Revalidate the geometry & image size xformImage = null; revalidate(); }
public void fitToRect( double width, double height ) { // System.err.println( "Fitting to " + width + ", " + height ); fitSize = true; maxWidth = width; maxHeight = height; // Revalidate the geometry & image size xformImage = null; revalidate(); repaint(); }
1,109,768
public void itemDeselected(SelectionEvent e) { changeToolTip(pp.getSelectedItems()); }
public void itemDeselected(SelectionEvent e) { setupAction(pp.getSelectedItems()); }
1,109,769
public void itemSelected(SelectionEvent e) { changeToolTip(pp.getSelectedItems()); }
public void itemSelected(SelectionEvent e) { setupAction(pp.getSelectedItems()); }
1,109,770
public static Project createProject() { Project project = new Project(); BuildLogger logger = new NoBannerLogger(); logger.setMessageOutputLevel( org.apache.tools.ant.Project.MSG_INFO ); logger.setOutputPrintStream( System.out ); logger.setErrorPrintStream( System.err); project.addBuildListener( logger ); project.init(); return project; }
public static Project createProject() { Project project = new Project(); BuildLogger logger = new NoBannerLogger(); logger.setMessageOutputLevel( org.apache.tools.ant.Project.MSG_INFO ); logger.setOutputPrintStream( System.out ); logger.setErrorPrintStream( System.err); project.addBuildListener( logger ); project.getBaseDir(); return project; }
1,109,772
public TagScript createRuntimeTaskTagScript(String taskName, Attributes attributes) throws Exception { TaskTag tag = new TaskTag( project, taskName ); return TagScript.newInstance( tag ); }
public TagScript createRuntimeTaskTagScript(String taskName, Attributes attributes) throws Exception { AntTag tag = new AntTag( project, taskName ); return TagScript.newInstance( tag ); }
1,109,773
public void doTag(final XMLOutput output) throws Exception { boolean available = false; if (file != null) { available = file.exists(); } else if (uri != null) { URL url = context.getResource(uri); String fileName = url.getFile(); File file = new File(fileName); available = file.exists(); } if (available) { invokeBody(output); } }
public void doTag(final XMLOutput output) throws Exception { boolean available = false; if (file != null) { available = file.exists(); } else if (uri != null) { URL url = context.getResource(uri); String fileName = url.getFile(); File file = new File(fileName); available = file.exists(); } if (available) { invokeBody(output); } }
1,109,776
public void addColumn(SQLColumn c, SQLTable t) throws ArchitectDiffException;
public void addColumn(SQLColumn c);
1,109,777
public abstract void addPrimaryKey(SQLTable t, String primaryKeyName) throws ArchitectException;
public abstract void addPrimaryKey(SQLTable t) throws ArchitectException;
1,109,778
public void addRelationship(SQLRelationship r) throws ArchitectDiffException;
public void addRelationship(SQLRelationship r);
1,109,779
public void dropColumn(SQLColumn c, SQLTable t) throws ArchitectDiffException;
public void dropColumn(SQLColumn c);
1,109,780
public abstract void dropPrimaryKey(SQLTable t, String primaryKeyName);
public abstract void dropPrimaryKey(SQLTable t);
1,109,781
public abstract List generateDDLStatements(SQLDatabase source) throws SQLException, ArchitectException;
public abstract List<DDLStatement> generateDDLStatements(SQLDatabase source) throws SQLException, ArchitectException;
1,109,782
public abstract String makeDropForeignKeySQL(String fkCatalog, String fkSchema, String fkTable, String fkName);
public abstract String makeDropForeignKeySQL(String fkTable, String fkName);
1,109,783
public abstract String makeDropTableSQL(String catalog, String schema, String table);
public abstract String makeDropTableSQL(String table);
1,109,784
public void modifyColumn(SQLColumn c) throws ArchitectDiffException ;
public void modifyColumn(SQLColumn c);
1,109,785
private void saveUser(){ try { Document doc = new Document(); Element rootElement = new Element(AuthConstants.JM_USERS); for(Iterator it=users.values().iterator(); it.hasNext();){ User user = (User)it.next(); /* create a user element */ Element userElement = new Element(AuthConstants.USER); userElement.setAttribute(AuthConstants.NAME, user.getUsername()); userElement.setAttribute(AuthConstants.PASSWORD, user.getPassword()); userElement.setAttribute(AuthConstants.STATUS, user.getStatus() != null ? user.getStatus() : "A"); userElement.setAttribute(AuthConstants.LOCK_COUNT, String.valueOf(user.getStatus() != null ? user.getLockCount() : 0)); /* add roles */ for(Iterator iterator = user.getRoles().iterator(); iterator.hasNext();){ Role role = (Role)iterator.next(); Element roleElement = new Element(AuthConstants.ROLE); roleElement.setText(role.getName()); userElement.addContent(roleElement); } rootElement.addContent(userElement); } doc.setRootElement(rootElement); /* write to the disc */ XMLOutputter writer = new XMLOutputter(); writer.output(doc, new FileOutputStream(AuthConstants.USER_CONFIG_FILE_NAME)); } catch (Exception e) { throw new RuntimeException(e); } }
private void saveUser(){ try { Document doc = new Document(); Element rootElement = new Element(AuthConstants.JM_USERS); for(Iterator it=users.values().iterator(); it.hasNext();){ User user = (User)it.next(); /* create a user element */ Element userElement = new Element(AuthConstants.USER); userElement.setAttribute(AuthConstants.NAME, user.getUsername()); userElement.setAttribute(AuthConstants.PASSWORD, user.getPassword()); userElement.setAttribute(AuthConstants.STATUS, user.getStatus() != null ? user.getStatus() : User.STATUS_ACTIVE); userElement.setAttribute(AuthConstants.LOCK_COUNT, String.valueOf(user.getStatus() != null ? user.getLockCount() : 0)); /* add roles */ for(Iterator iterator = user.getRoles().iterator(); iterator.hasNext();){ Role role = (Role)iterator.next(); Element roleElement = new Element(AuthConstants.ROLE); roleElement.setText(role.getName()); userElement.addContent(roleElement); } rootElement.addContent(userElement); } doc.setRootElement(rootElement); /* write to the disc */ XMLOutputter writer = new XMLOutputter(); writer.output(doc, new FileOutputStream(AuthConstants.USER_CONFIG_FILE_NAME)); } catch (Exception e) { throw new RuntimeException(e); } }
1,109,786
public User verifyUsernamePassword(String username, char[] password){ User user = (User)users.get(username); if(user != null){ final String hashedPassword = Crypto.hash(password); user = hashedPassword.equals(user.getPassword()) && "A".equals(user.getStatus()) ? user : null; } return user; }
public User verifyUsernamePassword(String username, char[] password){ User user = (User)users.get(username); if(user != null){ final String hashedPassword = Crypto.hash(password); user = hashedPassword.equals(user.getPassword()) && User.STATUS_ACTIVE.equals(user.getStatus()) ? user : null; } return user; }
1,109,787
private Result buildResult(Filter<S> filter, OrderingList<S> ordering) throws SupportException, RepositoryException { List<IndexedQueryAnalyzer<S>.Result> subResults; if (filter == null) { subResults = Collections.singletonList(mIndexAnalyzer.analyze(filter, ordering)); } else { subResults = splitIntoSubResults(filter, ordering); } if (subResults.size() <= 1) { // Total ordering not required. return new Result(subResults); } // If any orderings have an unspecified direction, switch to ASCENDING // or DESCENDING, depending on which is more popular. Then build new // sub-results. for (int pos = 0; pos < ordering.size(); pos++) { OrderedProperty<S> op = ordering.get(pos); if (op.getDirection() != Direction.UNSPECIFIED) { continue; } // Find out which direction is most popular for this property. Tally tally = new Tally(op.getChainedProperty()); for (IndexedQueryAnalyzer<S>.Result result : subResults) { tally.increment(findHandledDirection(result, op)); } ordering = ordering.replace(pos, op.direction(tally.getBestDirection())); // Re-calc with specified direction. Only do one property at a time // since one simple change might alter the query plan. subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. return new Result(subResults); } } // Gather all the keys available. As ordering properties touch key // properties, they are removed from all key sets. When a key set size // reaches zero, total ordering has been achieved. List<Set<ChainedProperty<S>>> keys = getKeys(); // Check if current ordering is total. for (OrderedProperty<S> op : ordering) { ChainedProperty<S> property = op.getChainedProperty(); if (pruneKeys(keys, property)) { // Found a key which is fully covered, indicating total ordering. return new Result(subResults, ordering); } } // Create a super key which contains all the properties required for // total ordering. The goal here is to append these properties to the // ordering in a fashion that takes advantage of each index's natural // ordering. This in turn should cause any sort operation to operate // over smaller groups. Smaller groups means smaller sort buffers. // Smaller sort buffers makes a merge sort happy. // Super key could be stored simply in a set, but a map makes it // convenient for tracking tallies. Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>(); for (Set<ChainedProperty<S>> key : keys) { for (ChainedProperty<S> property : key) { superKey.put(property, new Tally(property)); } } // Keep looping until total ordering achieved. while (true) { // For each ordering score, iterate over the entire unused ordering // properties and select the next free property. If property is in // the super key increment a tally associated with property // direction. Choose the property with the best tally and augment // the orderings with it and create new sub-results. Remove the // property from the super key and the key set. If any key is now // fully covered, a total ordering has been achieved. for (IndexedQueryAnalyzer<S>.Result result : subResults) { OrderingScore<S> score = result.getCompositeScore().getOrderingScore(); OrderingList<S> unused = score.getUnusedOrdering(); if (unused.size() > 0) { for (OrderedProperty<S> prop : unused) { ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } OrderingList<S> free = score.getFreeOrdering(); if (free.size() > 0) { OrderedProperty<S> prop = free.get(0); ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } Tally best = bestTally(superKey.values()); ChainedProperty<S> bestProperty = best.getProperty(); // Now augment the orderings and create new sub-results. ordering = ordering.concat(OrderedProperty.get(bestProperty, best.getBestDirection())); subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. break; } // Remove property from super key and key set... superKey.remove(bestProperty); if (superKey.size() == 0) { break; } if (pruneKeys(keys, bestProperty)) { break; } // Clear the tallies for the next run. for (Tally tally : superKey.values()) { tally.clear(); } } return new Result(subResults, ordering); }
private Result buildResult(Filter<S> filter, OrderingList<S> ordering) throws SupportException, RepositoryException { List<IndexedQueryAnalyzer<S>.Result> subResults; if (filter == null) { subResults = Collections.singletonList(mIndexAnalyzer.analyze(filter, ordering)); } else { subResults = splitIntoSubResults(filter, ordering); } if (subResults.size() <= 1) { // Total ordering not required. return new Result(subResults); } // If any orderings have an unspecified direction, switch to ASCENDING // or DESCENDING, depending on which is more popular. Then build new // sub-results. for (int pos = 0; pos < ordering.size(); pos++) { OrderedProperty<S> op = ordering.get(pos); if (op.getDirection() != Direction.UNSPECIFIED) { continue; } // Find out which direction is most popular for this property. Tally tally = new Tally(op.getChainedProperty()); for (IndexedQueryAnalyzer<S>.Result result : subResults) { tally.increment(findHandledDirection(result, op)); } ordering = ordering.replace(pos, op.direction(tally.getBestDirection())); // Re-calc with specified direction. Only do one property at a time // since one simple change might alter the query plan. subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. return new Result(subResults); } } // Gather all the keys available. As ordering properties touch key // properties, they are removed from all key sets. When a key set size // reaches zero, total ordering has been achieved. List<Set<ChainedProperty<S>>> keys = getKeys(); // Check if current ordering is total. for (OrderedProperty<S> op : ordering) { ChainedProperty<S> property = op.getChainedProperty(); if (pruneKeys(keys, property)) { // Found a key which is fully covered, indicating total ordering. return new Result(subResults, ordering); } } // Create a super key which contains all the properties required for // total ordering. The goal here is to append these properties to the // ordering in a fashion that takes advantage of each index's natural // ordering. This in turn should cause any sort operation to operate // over smaller groups. Smaller groups means smaller sort buffers. // Smaller sort buffers makes a merge sort happy. // Super key could be stored simply in a set, but a map makes it // convenient for tracking tallies. Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>(); for (Set<ChainedProperty<S>> key : keys) { for (ChainedProperty<S> property : key) { if (!superKey.containsKey(property)) { superKey.put(property, new Tally(property)); } } } // Keep looping until total ordering achieved. while (true) { // For each ordering score, iterate over the entire unused ordering // properties and select the next free property. If property is in // the super key increment a tally associated with property // direction. Choose the property with the best tally and augment // the orderings with it and create new sub-results. Remove the // property from the super key and the key set. If any key is now // fully covered, a total ordering has been achieved. for (IndexedQueryAnalyzer<S>.Result result : subResults) { OrderingScore<S> score = result.getCompositeScore().getOrderingScore(); OrderingList<S> unused = score.getUnusedOrdering(); if (unused.size() > 0) { for (OrderedProperty<S> prop : unused) { ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } OrderingList<S> free = score.getFreeOrdering(); if (free.size() > 0) { OrderedProperty<S> prop = free.get(0); ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } Tally best = bestTally(superKey.values()); ChainedProperty<S> bestProperty = best.getProperty(); // Now augment the orderings and create new sub-results. ordering = ordering.concat(OrderedProperty.get(bestProperty, best.getBestDirection())); subResults = splitIntoSubResults(filter, ordering); if (subResults.size() <= 1) { // Total ordering no longer required. break; } // Remove property from super key and key set... superKey.remove(bestProperty); if (superKey.size() == 0) { break; } if (pruneKeys(keys, bestProperty)) { break; } // Clear the tallies for the next run. for (Tally tally : superKey.values()) { tally.clear(); } } return new Result(subResults, ordering); }
1,109,788
private List<Set<ChainedProperty<S>>> getKeys() throws SupportException, RepositoryException { StorableInfo<S> info = StorableIntrospector.examine(mIndexAnalyzer.getStorableType()); List<Set<ChainedProperty<S>>> keys = new ArrayList<Set<ChainedProperty<S>>>(); keys.add(stripOrdering(info.getPrimaryKey().getProperties())); for (StorableKey<S> altKey : info.getAlternateKeys()) { keys.add(stripOrdering(altKey.getProperties())); } // Also fold in all unique indexes, just in case they weren't reported // as actual keys. Collection<StorableIndex<S>> indexes = mRepoAccess.storageAccessFor(getStorableType()).getAllIndexes(); for (StorableIndex<S> index : indexes) { if (!index.isUnique()) { continue; } int propCount = index.getPropertyCount(); Set<ChainedProperty<S>> props = new HashSet<ChainedProperty<S>>(propCount); for (int i=0; i<propCount; i++) { props.add(index.getOrderedProperty(i).getChainedProperty()); } keys.add(props); } return keys; }
private List<Set<ChainedProperty<S>>> getKeys() throws SupportException, RepositoryException { StorableInfo<S> info = StorableIntrospector.examine(mIndexAnalyzer.getStorableType()); List<Set<ChainedProperty<S>>> keys = new ArrayList<Set<ChainedProperty<S>>>(); keys.add(stripOrdering(info.getPrimaryKey().getProperties())); for (StorableKey<S> altKey : info.getAlternateKeys()) { keys.add(stripOrdering(altKey.getProperties())); } // Also fold in all unique indexes, just in case they weren't reported // as actual keys. Collection<StorableIndex<S>> indexes = mRepoAccess.storageAccessFor(getStorableType()).getAllIndexes(); for (StorableIndex<S> index : indexes) { if (!index.isUnique()) { continue; } int propCount = index.getPropertyCount(); Set<ChainedProperty<S>> props = new LinkedHashSet<ChainedProperty<S>>(propCount); for (int i=0; i<propCount; i++) { props.add(index.getOrderedProperty(i).getChainedProperty()); } keys.add(props); } return keys; }
1,109,789
private Set<ChainedProperty<S>> stripOrdering(Set<? extends OrderedProperty<S>> orderedProps) { Set<ChainedProperty<S>> props = new HashSet<ChainedProperty<S>>(orderedProps.size()); for (OrderedProperty<S> ordering : orderedProps) { props.add(ordering.getChainedProperty()); } return props; }
private Set<ChainedProperty<S>> stripOrdering(Set<? extends OrderedProperty<S>> orderedProps) { Set<ChainedProperty<S>> props = new LinkedHashSet<ChainedProperty<S>>(orderedProps.size()); for (OrderedProperty<S> ordering : orderedProps) { props.add(ordering.getChainedProperty()); } return props; }
1,109,790
public ActionForward execute(Exception exception, ExceptionConfig exConfig, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException { ActionErrors errors = new ActionErrors(); ActionForward forward; if(exception instanceof ServiceException){ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.WEB_UI_ERROR_KEY, exception.getMessage())); }else if(exception instanceof ConnectionFailedException){ //TODO: We need not handle this condition once all the code throwing this exception gets moved to service layer. // TODO: this is not right. We have a special page for such exceptions -rk errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.CONNECTION_FAILED)); }else{ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.UNKNOWN_ERROR)); } request.setAttribute(Globals.ERROR_KEY, errors); forward = mapping.getInputForward(); forward = forward != null && forward.getPath() != null ? forward : mapping.findForward(Forwards.FAILURE); forward = forward != null ? forward : new ActionForward(Forwards.FAILURE); return forward; }
public ActionForward execute(Exception exception, ExceptionConfig exConfig, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException { ActionErrors errors = new ActionErrors(); ActionForward forward; if(exception instanceof ServiceException){ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.WEB_UI_ERROR_KEY, exception.getMessage())); }else if(exception instanceof ConnectionFailedException){ //TODO: We need not handle this condition once all the code throwing this exception gets moved to service layer. // TODO: this is not right. We have a special page for such exceptions -rk errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.CONNECTION_FAILED)); }else{ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ErrorCodes.UNKNOWN_ERROR)); } request.setAttribute(Globals.ERROR_KEY, errors); forward = mapping.getInputForward(); forward = forward != null && forward.getPath() != null ? forward : mapping.findForward(Forwards.FAILURE); forward = forward != null ? forward : new ActionForward(Forwards.FAILURE); return forward; }
1,109,791
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; }
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { logger.debug("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; }
1,109,792
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; }
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; }
1,109,793
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; }
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { logger.debug("YES"); return flavors[i]; } } System.out.println("NO!"); return null; }
1,109,794
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } System.out.println("NO!"); return null; }
public DataFlavor bestImportFlavor(JComponent c, DataFlavor[] flavors) { System.out.println("PlayPenTransferHandler: can I import "+Arrays.asList(flavors)); for (int i = 0; i < flavors.length; i++) { String cls = flavors[i].getDefaultRepresentationClassAsString(); System.out.println("representation class = "+cls); System.out.println("mime type = "+flavors[i].getMimeType()); System.out.println("type = "+flavors[i].getPrimaryType()); System.out.println("subtype = "+flavors[i].getSubType()); System.out.println("class = "+flavors[i].getParameter("class")); System.out.println("isSerializedObject = "+flavors[i].isFlavorSerializedObjectType()); System.out.println("isInputStream = "+flavors[i].isRepresentationClassInputStream()); System.out.println("isRemoteObject = "+flavors[i].isFlavorRemoteObjectType()); System.out.println("isLocalObject = "+flavors[i].getMimeType().equals(DataFlavor.javaJVMLocalObjectMimeType)); if (flavors[i].equals(SQLObjectTransferable.flavor) || flavors[i].equals(SQLObjectListTransferable.flavor)) { System.out.println("YES"); return flavors[i]; } } logger.debug("NO!"); return null; }
1,109,795
public void dragOver(DropTargetDragEvent dtde) { System.out.println("PlayPenDropTarget.dragOver()"); dtde.acceptDrag(DnDConstants.ACTION_COPY); }
public void dragOver(DropTargetDragEvent dtde) { dtde.acceptDrag(DnDConstants.ACTION_COPY); }
1,109,796
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
1,109,797
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); logger.debug("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
1,109,798
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
1,109,799
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); System.out.println("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); JComponent c = (JComponent) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); System.out.println("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLTable table = (SQLTable) someData; TablePane tp = new TablePane(table); c.add(tp, dtde.getLocation()); tp.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
1,109,800
public void blockOut(int start, int length) { Block block = new Block(start, length); System.out.println("blockOut "+block+": before "+blocks); ListIterator it = blocks.listIterator(); while (it.hasNext()) { Block nextBlock = (Block) it.next(); if (nextBlock.start > start) { it.previous(); it.add(block); break; } } System.out.println("blockOut "+block+": after "+blocks); }
public void blockOut(int start, int length) { Block block = new Block(start, length); ListIterator it = blocks.listIterator(); while (it.hasNext()) { Block nextBlock = (Block) it.next(); if (nextBlock.start > start) { it.previous(); it.add(block); break; } } System.out.println("blockOut "+block+": after "+blocks); }
1,109,802
public void blockOut(int start, int length) { Block block = new Block(start, length); System.out.println("blockOut "+block+": before "+blocks); ListIterator it = blocks.listIterator(); while (it.hasNext()) { Block nextBlock = (Block) it.next(); if (nextBlock.start > start) { it.previous(); it.add(block); break; } } System.out.println("blockOut "+block+": after "+blocks); }
public void blockOut(int start, int length) { Block block = new Block(start, length); System.out.println("blockOut "+block+": before "+blocks); ListIterator it = blocks.listIterator(); while (it.hasNext()) { Block nextBlock = (Block) it.next(); if (nextBlock.start > start) { it.previous(); it.add(block); break; } } }
1,109,803
public int findGapToLeft(int start, int length) { int closestLeftGap = Integer.MIN_VALUE; int prevBlockEnd = Integer.MIN_VALUE; Iterator it = blocks.iterator(); while (it.hasNext()) { Block block = (Block) it.next(); if ( (prevBlockEnd < block.start - length) && (block.start - length <= start) ) { closestLeftGap = block.start - length; System.out.println("Updating leftGap = "+closestLeftGap); } if ( block.start > start ) { // we have reached a block to the right of start break; } prevBlockEnd = block.start + block.length; } // if we're still at one of the sentinel values, return the mouse location if (//closestLeftGap == Integer.MAX_VALUE-length || closestLeftGap == Integer.MIN_VALUE) { return start; } else { // otherwise, the answer is correct return closestLeftGap; } }
public int findGapToLeft(int start, int length) { int closestLeftGap = Integer.MIN_VALUE; int prevBlockEnd = Integer.MIN_VALUE; Iterator it = blocks.iterator(); while (it.hasNext()) { Block block = (Block) it.next(); if ( (prevBlockEnd < block.start - length) && (block.start - length <= start) ) { closestLeftGap = block.start - length; } if ( block.start > start ) { // we have reached a block to the right of start break; } prevBlockEnd = block.start + block.length; } // if we're still at one of the sentinel values, return the mouse location if (//closestLeftGap == Integer.MAX_VALUE-length || closestLeftGap == Integer.MIN_VALUE) { return start; } else { // otherwise, the answer is correct return closestLeftGap; } }
1,109,804
public int findGapToRight(int start, int length) { Iterator it = blocks.iterator(); while (it.hasNext()) { Block block = (Block) it.next(); if ( (start + length) < block.start ) { // current gap fits at right-hand side.. done! return start; } else { start = block.start + block.length; } } return start; }
public int findGapToRight(int start, int length) { Iterator it = blocks.iterator(); while (it.hasNext()) { Block block = (Block) it.next(); if ( (start + length) < block.start ) { // current gap fits at right-hand side.. done! return start; } else { start = Math.max(block.start + block.length, start); } } return start; }
1,109,805
public void layoutContainer(Container parent) { System.out.println("PlayPenLayout.layoutContainer"); }
public void layoutContainer(Container parent) { logger.debug("PlayPenLayout.layoutContainer"); }
1,109,806
public void removeLayoutComponent(Component comp) { System.out.println("PlayPenLayout.removeLayoutComponent"); }
public void removeLayoutComponent(Component comp) { logger.debug("PlayPenLayout.removeLayoutComponent"); }
1,109,807