rem
stringlengths
0
477k
add
stringlengths
0
313k
context
stringlengths
6
599k
}); JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER)); p.add(abortButton); add(p, BorderLayout.SOUTH);
} }; abortAction.setEnabled(true); font = new Font("Courier New", Font.PLAIN, 12 );
public EngineExecPanel(String header, Process pr) { super(new BorderLayout()); proc = pr; abortButton = new JButton("Abort"); abortButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { proc.destroy(); } }); JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER)); p.add(abortButton); add(p, BorderLayout.SOUTH); output = new JTextArea(25, 80); output.append(header); add(new JScrollPane(output), BorderLayout.CENTER); InputStream pis = new BufferedInputStream(proc.getInputStream()); InputStream pes = new BufferedInputStream(proc.getErrorStream()); iss = new Thread(new StreamSink(pis)); ess = new Thread(new StreamSink(pes)); iss.start(); ess.start(); }
output = new JTextArea(25, 80);
output = new JTextArea(25, 120);
public EngineExecPanel(String header, Process pr) { super(new BorderLayout()); proc = pr; abortButton = new JButton("Abort"); abortButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { proc.destroy(); } }); JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER)); p.add(abortButton); add(p, BorderLayout.SOUTH); output = new JTextArea(25, 80); output.append(header); add(new JScrollPane(output), BorderLayout.CENTER); InputStream pis = new BufferedInputStream(proc.getInputStream()); InputStream pes = new BufferedInputStream(proc.getErrorStream()); iss = new Thread(new StreamSink(pis)); ess = new Thread(new StreamSink(pes)); iss.start(); ess.start(); }
Runnable buttonEnabler = new Runnable() { public void run() { waitForProcessCompletion(); SwingUtilities.invokeLater(new Runnable() { public void run() { abortAction.setEnabled(false); } }); } }; new Thread(buttonEnabler).start();
public EngineExecPanel(String header, Process pr) { super(new BorderLayout()); proc = pr; abortButton = new JButton("Abort"); abortButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { proc.destroy(); } }); JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER)); p.add(abortButton); add(p, BorderLayout.SOUTH); output = new JTextArea(25, 80); output.append(header); add(new JScrollPane(output), BorderLayout.CENTER); InputStream pis = new BufferedInputStream(proc.getInputStream()); InputStream pes = new BufferedInputStream(proc.getErrorStream()); iss = new Thread(new StreamSink(pis)); ess = new Thread(new StreamSink(pes)); iss.start(); ess.start(); }
proc.destroy();
proc.destroy(); if ( output != null && output.isEnabled() ) { output.append("Aborted ..."); output.setEnabled(false);
public void actionPerformed(ActionEvent e) { proc.destroy(); }
}
public void actionPerformed(ActionEvent e) { proc.destroy(); }
abortButton.setEnabled(false);
public void waitForProcessCompletion() { try { iss.join(); ess.join(); } catch (InterruptedException ex) { System.out.println("Interrupted while waiting for engine"); } abortButton.setEnabled(false); output.append("Execution halted"); }
super("Create Table",
super("New Table",
public CreateTableAction() { super("Create Table", ASUtils.createIcon("NewTable", "Create Table", ArchitectFrame.getMainInstance().sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))); }
"Create Table",
"New Table",
public CreateTableAction() { super("Create Table", ASUtils.createIcon("NewTable", "Create Table", ArchitectFrame.getMainInstance().sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))); }
putValue(SHORT_DESCRIPTION, "New Table");
public CreateTableAction() { super("Create Table", ASUtils.createIcon("NewTable", "Create Table", ArchitectFrame.getMainInstance().sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))); }
if(paramValues == null) paramValues = new HashMap();
public Map getParamValues(){ return paramValues; }
Font detailsFont = new Font("Default", Font.BOLD, 12);
Font detailsFont = new Font("Default", Font.PLAIN, 14);
public static void main(String[] args) { //set defaults Options.setMissingThreshold(0.5); Options.setSpacingThreshold(0.0); Options.setAssocTest(ASSOC_NONE); Options.setHaplotypeDisplayThreshold(1); Options.setMaxDistance(500); Options.setLDColorScheme(STD_SCHEME); Options.setShowGBrowse(false); //this parses the command line arguments. if nogui mode is specified, //then haploText will execute whatever the user specified HaploText argParser = new HaploText(args); //if nogui is specified, then HaploText has already executed everything, and let Main() return //otherwise, we want to actually load and run the gui if(!argParser.isNogui()) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } //System.setProperty("swing.disableFileChooserSpeedFix", "true"); window = new HaploView(); //setup view object window.setTitle(TITLE_STRING); window.setSize(800,600); final SwingWorker worker = new SwingWorker(){ UpdateChecker uc; public Object construct() { uc = new UpdateChecker(); uc.checkForUpdate(); return null; } public void finished() { if(uc != null) { if(uc.isNewVersionAvailable()) { //theres an update available so lets pop some crap up final JLayeredPane jlp = window.getLayeredPane(); final JPanel udp = new JPanel(); udp.setLayout(new BoxLayout(udp, BoxLayout.Y_AXIS)); double version = uc.getNewVersion(); Font detailsFont = new Font("Default", Font.BOLD, 12); JLabel announceLabel = new JLabel("A newer version of Haploview (" +version+") is available."); announceLabel.setFont(detailsFont); JLabel detailsLabel = new JLabel("See \"Check for update\" in the file menu for details."); detailsLabel.setFont(detailsFont); udp.add(announceLabel); udp.add(detailsLabel); udp.setBorder(BorderFactory.createRaisedBevelBorder()); int width = udp.getPreferredSize().width; int height = udp.getPreferredSize().height; int borderwidth = udp.getBorder().getBorderInsets(udp).right; int borderheight = udp.getBorder().getBorderInsets(udp).bottom; udp.setBounds(jlp.getWidth()-width-borderwidth, jlp.getHeight()-height-borderheight, udp.getPreferredSize().width, udp.getPreferredSize().height); udp.setOpaque(true); jlp.add(udp, JLayeredPane.POPUP_LAYER); java.util.Timer updateTimer = new Timer(); //show this update message for 6.5 seconds updateTimer.schedule(new TimerTask() { public void run() { jlp.remove(udp); jlp.repaint(); } },6000); } } } }; //center the window on the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation((screen.width - window.getWidth()) / 2, (screen.height - window.getHeight()) / 2); window.setVisible(true); worker.start(); //parse command line stuff for input files or prompt data dialog String[] inputArray = new String[2]; if (argParser.getHapsFileName() != null){ inputArray[0] = argParser.getHapsFileName(); inputArray[1] = argParser.getInfoFileName(); window.readGenotypes(inputArray, HAPS); }else if (argParser.getPedFileName() != null){ inputArray[0] = argParser.getPedFileName(); inputArray[1] = argParser.getInfoFileName(); window.readGenotypes(inputArray, PED); }else if (argParser.getHapmapFileName() != null){ inputArray[0] = argParser.getHapmapFileName(); inputArray[1] = ""; window.readGenotypes(inputArray, HMP); }else{ ReadDataDialog readDialog = new ReadDataDialog("Welcome to HaploView", window); readDialog.pack(); readDialog.setVisible(true); } } }
Font detailsFont = new Font("Default", Font.BOLD, 12);
Font detailsFont = new Font("Default", Font.PLAIN, 14);
public void finished() { if(uc != null) { if(uc.isNewVersionAvailable()) { //theres an update available so lets pop some crap up final JLayeredPane jlp = window.getLayeredPane(); final JPanel udp = new JPanel(); udp.setLayout(new BoxLayout(udp, BoxLayout.Y_AXIS)); double version = uc.getNewVersion(); Font detailsFont = new Font("Default", Font.BOLD, 12); JLabel announceLabel = new JLabel("A newer version of Haploview (" +version+") is available."); announceLabel.setFont(detailsFont); JLabel detailsLabel = new JLabel("See \"Check for update\" in the file menu for details."); detailsLabel.setFont(detailsFont); udp.add(announceLabel); udp.add(detailsLabel); udp.setBorder(BorderFactory.createRaisedBevelBorder()); int width = udp.getPreferredSize().width; int height = udp.getPreferredSize().height; int borderwidth = udp.getBorder().getBorderInsets(udp).right; int borderheight = udp.getBorder().getBorderInsets(udp).bottom; udp.setBounds(jlp.getWidth()-width-borderwidth, jlp.getHeight()-height-borderheight, udp.getPreferredSize().width, udp.getPreferredSize().height); udp.setOpaque(true); jlp.add(udp, JLayeredPane.POPUP_LAYER); java.util.Timer updateTimer = new Timer(); //show this update message for 6.5 seconds updateTimer.schedule(new TimerTask() { public void run() { jlp.remove(udp); jlp.repaint(); } },6000); } } }
try { connection.close(); } catch (IOException e) { logger.log(Level.WARNING, "Error while closing connection. error: " + e.getMessage()); }
closeConnection();
private void connectionClosed(){ try { this.unregisterInternal(); } catch (Exception e) { logger.severe("Error unregistering for monitoring. error=" + e.getMessage()); } /* close the connection */ try { connection.close(); } catch (IOException e) { logger.log(Level.WARNING, "Error while closing connection. error: " + e.getMessage()); } /* need to re-establish the connection when the server comes up */ new EstablishConnection().start(); }
logger.severe("Error registering for monitoring. error=" + e.getMessage()); new EstablishConnection().start();
logger.log(Level.SEVERE, "Error registering alert: " + alertName, e); closeConnection();
private void connectionOpen(){ try { /* start monitoring */ registerInternal(); logger.info("Registered for alert: " + alertName + ", application: " + sourceConfig.getApplicationConfig().getName()); } catch (Exception e) { logger.severe("Error registering for monitoring. error=" + e.getMessage()); /* need to re-establish the connection when the server comes up */ new EstablishConnection().start(); return; } /* start the connection monitoring thread */ new ConnectionMonitor().start(); }
double[][] alleleCounts = new double[filteredHaplos[i][0].getGeno().length][9]; for (int j = 0; j < alleleCounts.length; j++){ for (int k = 0; k < alleleCounts[j].length; k++){ alleleCounts[j][k] = 0; } } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); double theFreq = filteredHaplos[i][curHapNum].getPercentage(); for (int k = 0; k < theGeno.length; k++){ alleleCounts[k][theGeno[k]] += theFreq; } }
public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.setColor(this.getBackground()); g.fillRect(0,0,pref.width, pref.height); if (!forExport){ g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(Locale.US); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(Locale.US); int markerCount = Chromosome.getSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; //block labels g.setColor(Color.black); g.drawString("Block " + (i+1), left, top - CHAR_HEIGHT); for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(Chromosome.realIndex[markerNums[z]]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; //figure out which allele is the major allele double[][] alleleCounts = new double[filteredHaplos[i][0].getGeno().length][9]; //zero this out for (int j = 0; j < alleleCounts.length; j++){ for (int k = 0; k < alleleCounts[j].length; k++){ alleleCounts[j][k] = 0; } } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); double theFreq = filteredHaplos[i][curHapNum].getPercentage(); for (int k = 0; k < theGeno.length; k++){ alleleCounts[k][theGeno[k]] += theFreq; } } int[] majorAllele = new int[filteredHaplos[i][0].getGeno().length]; for (int k = 0; k < majorAllele.length; k++){ double maj = 0; for (int z = 0; z < alleleCounts[k].length; z++){ if (alleleCounts[k][z] > maj){ majorAllele[k] = z; maj = alleleCounts[k][z]; } } } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) if (alleleDisp == 0){ g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else if (alleleDisp == 1){ g.drawImage(blackNumImages[theGeno[k]], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else{ if (theGeno[k] == majorAllele[k]){ g.setColor(dullBlue); }else{ g.setColor(dullRed); } g.fillRect(left + k*CHAR_WIDTH, above + j*ROW_HEIGHT + (ROW_HEIGHT - CHAR_WIDTH)/2, CHAR_WIDTH, CHAR_WIDTH); } } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines int crossValue = (int) (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); if (multidprimeArray[i] > 0.99){ //draw 1.0 vals specially g.drawImage(blackNumImages[1], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[10], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 2*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[0], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 3*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); }else{ for (int m = 0; m < 3; m++) { g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } } } left += LINE_SPAN; } }
double maj = 0; for (int z = 0; z < alleleCounts[k].length; z++){ if (alleleCounts[k][z] > maj){ majorAllele[k] = z; maj = alleleCounts[k][z]; } }
majorAllele[k] = Chromosome.getFilteredMarker(markerNums[k]).getMajor();
public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.setColor(this.getBackground()); g.fillRect(0,0,pref.width, pref.height); if (!forExport){ g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(Locale.US); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(Locale.US); int markerCount = Chromosome.getSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; //block labels g.setColor(Color.black); g.drawString("Block " + (i+1), left, top - CHAR_HEIGHT); for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(Chromosome.realIndex[markerNums[z]]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; //figure out which allele is the major allele double[][] alleleCounts = new double[filteredHaplos[i][0].getGeno().length][9]; //zero this out for (int j = 0; j < alleleCounts.length; j++){ for (int k = 0; k < alleleCounts[j].length; k++){ alleleCounts[j][k] = 0; } } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); double theFreq = filteredHaplos[i][curHapNum].getPercentage(); for (int k = 0; k < theGeno.length; k++){ alleleCounts[k][theGeno[k]] += theFreq; } } int[] majorAllele = new int[filteredHaplos[i][0].getGeno().length]; for (int k = 0; k < majorAllele.length; k++){ double maj = 0; for (int z = 0; z < alleleCounts[k].length; z++){ if (alleleCounts[k][z] > maj){ majorAllele[k] = z; maj = alleleCounts[k][z]; } } } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) if (alleleDisp == 0){ g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else if (alleleDisp == 1){ g.drawImage(blackNumImages[theGeno[k]], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else{ if (theGeno[k] == majorAllele[k]){ g.setColor(dullBlue); }else{ g.setColor(dullRed); } g.fillRect(left + k*CHAR_WIDTH, above + j*ROW_HEIGHT + (ROW_HEIGHT - CHAR_WIDTH)/2, CHAR_WIDTH, CHAR_WIDTH); } } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines int crossValue = (int) (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); if (multidprimeArray[i] > 0.99){ //draw 1.0 vals specially g.drawImage(blackNumImages[1], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[10], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 2*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[0], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 3*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); }else{ for (int m = 0; m < 3; m++) { g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } } } left += LINE_SPAN; } }
ODMGXAWrapper txw = new ODMGXAWrapper();
log.debug( "Creating instance " + imgFile.getAbsolutePath() ); ODMGXAWrapper txw = new ODMGXAWrapper();
public static ImageInstance create ( VolumeBase vol, File imgFile ) { ODMGXAWrapper txw = new ODMGXAWrapper(); ImageInstance i = new ImageInstance(); i.volume = vol; i.volumeId = vol.getName(); i.imageFile = imgFile; i.fileSize = imgFile.length(); i.mtime = imgFile.lastModified(); i.fname = vol.mapFileToVolumeRelativeName( imgFile ); txw.lock( i, Transaction.WRITE ); // Read the rest of fields from the image file try { i.readImageFile(); } catch (IOException e ) { txw.abort(); log.warn( "Error opening image file: " + e.getMessage() ); // The image does not exist, so it cannot be read!!! return null; } i.calcHash(); i.checkTime = new java.util.Date(); txw.commit(); return i; }
Iterator readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader)readers.next();
String fname = imageFile.getName(); int lastDotPos = fname.lastIndexOf( "." ); if ( lastDotPos <= 0 || lastDotPos >= fname.length()-1 ) { throw new IOException( "Cannot determine file type extension of " + imageFile.getAbsolutePath() ); } String suffix = fname.substring( lastDotPos+1 ); Iterator readers = ImageIO.getImageReadersBySuffix( suffix ); if ( !readers.hasNext() ) { throw new IOException( "Unknown image file extension " + suffix + "\nwhile reading " + imageFile.getAbsolutePath() ); } ImageReader reader = (ImageReader)readers.next();
protected void readImageFile() throws IOException { // Find the JPEG image reader // TODO: THis shoud decode also other readers from fname Iterator readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader)readers.next(); ImageInputStream iis = null; try { iis = ImageIO.createImageInputStream( imageFile ); if ( iis != null ) { reader.setInput( iis, true ); width = reader.getWidth( 0 ); height = reader.getHeight( 0 ); reader.dispose(); } } catch (IOException ex) { log.debug( "Exception in readImageFile: " + ex.getMessage() ); throw ex; } finally { if ( iis != null ) { try { iis.close(); } catch (IOException ex) { log.warn( "Cannot close image stream: " + ex.getMessage() ); } } } }
new TextMethods().saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile);
textData.saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile);
private void processFile(String fileName,boolean fileType,String infoFileName){ try { int outputType; long maxDistance; HaploData textData; File OutputFile; File inputFile; inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } maxDistance = this.arg_distance * 1000; outputType = this.arg_output; switch(outputType){ case 1: OutputFile = new File(fileName + ".4GAMblocks"); break; case 2: OutputFile = new File(fileName + ".MJDblocks"); break; default: OutputFile = new File(fileName + ".SFSblocks"); break; } textData = new HaploData(); if(!fileType){ //read in haps file textData.prepareHapsInput(inputFile); } else { //read in ped file PedFile ped; Vector pedFileStrings; BufferedReader reader; String line; Vector result; boolean[] markerResultArray; ped = new PedFile(); pedFileStrings = new Vector(); reader = new BufferedReader(new FileReader(inputFile)); result = new Vector(); while((line = reader.readLine())!=null){ pedFileStrings.add(line); } ped.parse(pedFileStrings); if(!arg_skipCheck) { result = ped.check(); } if(this.arg_showCheck) { System.out.println("Data check results:\n" + "Name\t\tObsHET\tPredHET\tHWpval\t%Geno\tFamTrio\tMendErr"); for(int i=0;i<result.size();i++){ MarkerResult currentResult = (MarkerResult)result.get(i); System.out.println( currentResult.getName() +"\t"+ currentResult.getObsHet() +"\t"+ currentResult.getPredHet() +"\t"+ currentResult.getHWpvalue() +"\t"+ currentResult.getGenoPercent() +"\t"+ currentResult.getFamTrioNum() +"\t"+ currentResult.getMendErrNum()); } } markerResultArray = new boolean[ped.getNumMarkers()]; for (int i = 0; i < markerResultArray.length; i++){ if(this.arg_skipCheck) { markerResultArray[i] = true; } else if(((MarkerResult)result.get(i)).getRating() > 0) { markerResultArray[i] = true; } else { markerResultArray[i] = false; } } 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[i] = false; if(!this.arg_quiet) { System.out.println("Ignoring marker " + (i+1)); } } } } textData.linkageToChrom(markerResultArray,ped); } String name = fileName; String baseName = fileName.substring(0,name.length()-5); if(!infoFileName.equals("")) { File infoFile = new File(infoFileName); if(infoFile.exists()) { textData.prepareMarkerInput(infoFile,maxDistance); System.out.println("Using marker file " + infoFile.getName()); } else if(!this.arg_quiet) { System.out.println("info file " + infoFileName + " does not exist"); } } else { File maybeInfo = new File(baseName + ".info"); if (maybeInfo.exists()){ textData.prepareMarkerInput(maybeInfo,maxDistance); if(!arg_quiet){ System.out.println("Using marker file " + maybeInfo.getName()); } } } textData.generateDPrimeTable(maxDistance); Haplotype[][] haplos; textData.guessBlocks(outputType); haplos = textData.generateHaplotypes(textData.blocks, 1); new TextMethods().saveHapsToText(orderHaps(haplos, textData), textData.getMultiDprime(), OutputFile); } catch(IOException e){} catch(HaploViewException e){ System.out.println(e.getMessage()); } }
Arrays.sort(theBlock);
Haplotype[][] generateHaplotypes(Vector blocks, int hapthresh) throws HaploViewException{ //TODO: output indiv hap estimates Haplotype[][] results = new Haplotype[blocks.size()][]; //String raw = new String(); //String currentLine; this.totalBlocks = blocks.size(); this.blocksDone = 0; for (int k = 0; k < blocks.size(); k++){ this.blocksDone++; int[] preFiltBlock = (int[])blocks.elementAt(k); int[] theBlock; int[] selectedMarkers = new int[0]; int[] equivClass = new int[0]; if (preFiltBlock.length > 30){ equivClass = new int[preFiltBlock.length]; int classCounter = 0; for (int x = 0; x < preFiltBlock.length; x++){ int marker1 = preFiltBlock[x]; //already been lumped into an equivalency class if (equivClass[x] != 0){ continue; } //start a new equivalency class for this SNP classCounter ++; equivClass[x] = classCounter; for (int y = x+1; y < preFiltBlock.length; y++){ int marker2 = preFiltBlock[y]; if (marker1 > marker2){ int tmp = marker1; marker1 = marker2; marker2 = tmp; } if (filteredDPrimeTable[marker1][marker2].getRSquared() == 1.0){ //these two SNPs are redundant equivClass[y] = classCounter; } } } //parse equivalency classes selectedMarkers = new int[classCounter]; for (int x = 0; x < selectedMarkers.length; x++){ selectedMarkers[x] = -1; } for (int x = 0; x < classCounter; x++){ double genoPC = 1.0; for (int y = 0; y < equivClass.length; y++){ if (equivClass[y] == x+1){ //int[]tossed = new int[3]; if (percentBadGenotypes[preFiltBlock[y]] < genoPC){ selectedMarkers[x] = preFiltBlock[y]; genoPC = percentBadGenotypes[preFiltBlock[y]]; } } } } theBlock = selectedMarkers; Arrays.sort(theBlock); //System.out.println("Block " + k + " " + theBlock.length + "/" + preFiltBlock.length); }else{ theBlock = preFiltBlock; } //break up large blocks if needed int[] block_size; if (theBlock.length < 9){ block_size = new int[1]; block_size[0] = theBlock.length; } else { //some base-8 arithmetic int ones = theBlock.length%8; int eights = (theBlock.length - ones)/8; if (ones == 0){ block_size = new int[eights]; for (int i = 0; i < eights; i++){ block_size[i]=8; } } else { block_size = new int[eights+1]; for (int i = 0; i < eights-1; i++){ block_size[i]=8; } block_size[eights-1] = (8+ones)/2; block_size[eights] = 8+ones-block_size[eights-1]; } } byte[] thisHap; Vector inputHaploVector = new Vector(); for (int i = 0; i < chromosomes.size(); i++){ thisHap = new byte[theBlock.length]; Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); boolean tooManyMissingInASegment = false; int totalMissing = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missing = 0; for (int j = 0; j < block_size[n]; j++){ byte theGeno = thisChrom.getFilteredGenotype(theBlock[segmentShift+j]); byte nextGeno = nextChrom.getFilteredGenotype(theBlock[segmentShift+j]); if(theGeno == 0 || nextGeno == 0) missing++; } segmentShift += block_size[n]; if (missing >= missingLimit){ tooManyMissingInASegment = true; } totalMissing += missing; } //we want to use chromosomes without too many missing genotypes in a given //subsegment (first term) or without too many missing genotypes in the //whole block (second term) if (!tooManyMissingInASegment && totalMissing <= 1+theBlock.length/3){ for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); byte theGeno = thisChrom.getFilteredGenotype(theBlock[j]); if (theGeno >= 5){ thisHap[j] = 'h'; } else { if (theGeno == a1){ thisHap[j] = '1'; }else if (theGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } inputHaploVector.add(thisHap); thisHap = new byte[theBlock.length]; for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); byte nextGeno = nextChrom.getFilteredGenotype(theBlock[j]); if (nextGeno >= 5){ thisHap[j] = 'h'; } else { if (nextGeno == a1){ thisHap[j] = '1'; }else if (nextGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } inputHaploVector.add(thisHap); } } byte[][] input_haplos = (byte[][])inputHaploVector.toArray(new byte[0][0]); String EMreturn = new String(""); int[] num_haplos_present = new int[1]; Vector haplos_present = new Vector(); Vector haplo_freq = new Vector(); //kirby patch EM theEM = new EM(); theEM.full_em_breakup(input_haplos, 4, num_haplos_present, haplos_present, haplo_freq, block_size, 0); for (int j = 0; j < haplos_present.size(); j++){ EMreturn += (String)haplos_present.elementAt(j)+"\t"+(String)haplo_freq.elementAt(j)+"\t"; } StringTokenizer st = new StringTokenizer(EMreturn); int p = 0; Haplotype[] tempArray = new Haplotype[st.countTokens()/2]; while(st.hasMoreTokens()){ String aString = st.nextToken(); int[] genos = new int[aString.length()]; for (int j = 0; j < aString.length(); j++){ byte returnBit = Byte.parseByte(aString.substring(j,j+1)); if (returnBit == 1){ genos[j] = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); }else{ if (Chromosome.getFilteredMarker(theBlock[j]).getMinor() == 0){ genos[j] = 8; }else{ genos[j] = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); } } } if (selectedMarkers.length > 0){ //we need to reassemble the haplotypes Hashtable hapsHash = new Hashtable(); //add to hash all the genotypes we phased for (int q = 0; q < genos.length; q++){ hapsHash.put(new Integer(theBlock[q]), new Integer(genos[q])); } //now add all the genotypes we didn't bother phasing, based on //which marker they are identical to for (int q = 0; q < equivClass.length; q++){ int currentClass = equivClass[q]-1; if (selectedMarkers[currentClass] == preFiltBlock[q]){ //we alredy added the phased genotypes above continue; } int indexIntoBlock=0; for (int x = 0; x < theBlock.length; x++){ if (theBlock[x] == selectedMarkers[currentClass]){ indexIntoBlock = x; break; } } //this (somewhat laboriously) reconstructs whether to add the minor or major allele if (Chromosome.getFilteredMarker(selectedMarkers[currentClass]).getMajor() == genos[indexIntoBlock]){ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMajor())); }else{ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMinor())); } } genos = new int[preFiltBlock.length]; for (int q = 0; q < preFiltBlock.length; q++){ genos[q] = ((Integer)hapsHash.get(new Integer(preFiltBlock[q]))).intValue(); } } double tempPerc = Double.parseDouble(st.nextToken()); if (tempPerc*100 > hapthresh){ tempArray[p] = new Haplotype(genos, tempPerc, preFiltBlock); p++; } } //make the results array only large enough to hold haps //which pass threshold above results[k] = new Haplotype[p]; for (int z = 0; z < p; z++){ results[k][z] = tempArray[z]; } } return results; }
if (Chromosome.getFilteredMarker(selectedMarkers[currentClass]).getMajor() == genos[indexIntoBlock]){ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMajor()));
if (Chromosome.getFilteredMarker(selectedMarkers[currentClass]).getMAF() > 0.4){ for (int i = 0; i < chromosomes.size(); i++){ Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); int theGeno = thisChrom.getFilteredGenotype(selectedMarkers[currentClass]); int nextGeno = nextChrom.getFilteredGenotype(selectedMarkers[currentClass]); if (theGeno == nextGeno && theGeno == genos[indexIntoBlock] && thisChrom.getFilteredGenotype(preFiltBlock[q]) != 0){ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(thisChrom.getFilteredGenotype(preFiltBlock[q]))); } }
Haplotype[][] generateHaplotypes(Vector blocks, int hapthresh) throws HaploViewException{ //TODO: output indiv hap estimates Haplotype[][] results = new Haplotype[blocks.size()][]; //String raw = new String(); //String currentLine; this.totalBlocks = blocks.size(); this.blocksDone = 0; for (int k = 0; k < blocks.size(); k++){ this.blocksDone++; int[] preFiltBlock = (int[])blocks.elementAt(k); int[] theBlock; int[] selectedMarkers = new int[0]; int[] equivClass = new int[0]; if (preFiltBlock.length > 30){ equivClass = new int[preFiltBlock.length]; int classCounter = 0; for (int x = 0; x < preFiltBlock.length; x++){ int marker1 = preFiltBlock[x]; //already been lumped into an equivalency class if (equivClass[x] != 0){ continue; } //start a new equivalency class for this SNP classCounter ++; equivClass[x] = classCounter; for (int y = x+1; y < preFiltBlock.length; y++){ int marker2 = preFiltBlock[y]; if (marker1 > marker2){ int tmp = marker1; marker1 = marker2; marker2 = tmp; } if (filteredDPrimeTable[marker1][marker2].getRSquared() == 1.0){ //these two SNPs are redundant equivClass[y] = classCounter; } } } //parse equivalency classes selectedMarkers = new int[classCounter]; for (int x = 0; x < selectedMarkers.length; x++){ selectedMarkers[x] = -1; } for (int x = 0; x < classCounter; x++){ double genoPC = 1.0; for (int y = 0; y < equivClass.length; y++){ if (equivClass[y] == x+1){ //int[]tossed = new int[3]; if (percentBadGenotypes[preFiltBlock[y]] < genoPC){ selectedMarkers[x] = preFiltBlock[y]; genoPC = percentBadGenotypes[preFiltBlock[y]]; } } } } theBlock = selectedMarkers; Arrays.sort(theBlock); //System.out.println("Block " + k + " " + theBlock.length + "/" + preFiltBlock.length); }else{ theBlock = preFiltBlock; } //break up large blocks if needed int[] block_size; if (theBlock.length < 9){ block_size = new int[1]; block_size[0] = theBlock.length; } else { //some base-8 arithmetic int ones = theBlock.length%8; int eights = (theBlock.length - ones)/8; if (ones == 0){ block_size = new int[eights]; for (int i = 0; i < eights; i++){ block_size[i]=8; } } else { block_size = new int[eights+1]; for (int i = 0; i < eights-1; i++){ block_size[i]=8; } block_size[eights-1] = (8+ones)/2; block_size[eights] = 8+ones-block_size[eights-1]; } } byte[] thisHap; Vector inputHaploVector = new Vector(); for (int i = 0; i < chromosomes.size(); i++){ thisHap = new byte[theBlock.length]; Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); boolean tooManyMissingInASegment = false; int totalMissing = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missing = 0; for (int j = 0; j < block_size[n]; j++){ byte theGeno = thisChrom.getFilteredGenotype(theBlock[segmentShift+j]); byte nextGeno = nextChrom.getFilteredGenotype(theBlock[segmentShift+j]); if(theGeno == 0 || nextGeno == 0) missing++; } segmentShift += block_size[n]; if (missing >= missingLimit){ tooManyMissingInASegment = true; } totalMissing += missing; } //we want to use chromosomes without too many missing genotypes in a given //subsegment (first term) or without too many missing genotypes in the //whole block (second term) if (!tooManyMissingInASegment && totalMissing <= 1+theBlock.length/3){ for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); byte theGeno = thisChrom.getFilteredGenotype(theBlock[j]); if (theGeno >= 5){ thisHap[j] = 'h'; } else { if (theGeno == a1){ thisHap[j] = '1'; }else if (theGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } inputHaploVector.add(thisHap); thisHap = new byte[theBlock.length]; for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); byte nextGeno = nextChrom.getFilteredGenotype(theBlock[j]); if (nextGeno >= 5){ thisHap[j] = 'h'; } else { if (nextGeno == a1){ thisHap[j] = '1'; }else if (nextGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } inputHaploVector.add(thisHap); } } byte[][] input_haplos = (byte[][])inputHaploVector.toArray(new byte[0][0]); String EMreturn = new String(""); int[] num_haplos_present = new int[1]; Vector haplos_present = new Vector(); Vector haplo_freq = new Vector(); //kirby patch EM theEM = new EM(); theEM.full_em_breakup(input_haplos, 4, num_haplos_present, haplos_present, haplo_freq, block_size, 0); for (int j = 0; j < haplos_present.size(); j++){ EMreturn += (String)haplos_present.elementAt(j)+"\t"+(String)haplo_freq.elementAt(j)+"\t"; } StringTokenizer st = new StringTokenizer(EMreturn); int p = 0; Haplotype[] tempArray = new Haplotype[st.countTokens()/2]; while(st.hasMoreTokens()){ String aString = st.nextToken(); int[] genos = new int[aString.length()]; for (int j = 0; j < aString.length(); j++){ byte returnBit = Byte.parseByte(aString.substring(j,j+1)); if (returnBit == 1){ genos[j] = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); }else{ if (Chromosome.getFilteredMarker(theBlock[j]).getMinor() == 0){ genos[j] = 8; }else{ genos[j] = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); } } } if (selectedMarkers.length > 0){ //we need to reassemble the haplotypes Hashtable hapsHash = new Hashtable(); //add to hash all the genotypes we phased for (int q = 0; q < genos.length; q++){ hapsHash.put(new Integer(theBlock[q]), new Integer(genos[q])); } //now add all the genotypes we didn't bother phasing, based on //which marker they are identical to for (int q = 0; q < equivClass.length; q++){ int currentClass = equivClass[q]-1; if (selectedMarkers[currentClass] == preFiltBlock[q]){ //we alredy added the phased genotypes above continue; } int indexIntoBlock=0; for (int x = 0; x < theBlock.length; x++){ if (theBlock[x] == selectedMarkers[currentClass]){ indexIntoBlock = x; break; } } //this (somewhat laboriously) reconstructs whether to add the minor or major allele if (Chromosome.getFilteredMarker(selectedMarkers[currentClass]).getMajor() == genos[indexIntoBlock]){ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMajor())); }else{ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMinor())); } } genos = new int[preFiltBlock.length]; for (int q = 0; q < preFiltBlock.length; q++){ genos[q] = ((Integer)hapsHash.get(new Integer(preFiltBlock[q]))).intValue(); } } double tempPerc = Double.parseDouble(st.nextToken()); if (tempPerc*100 > hapthresh){ tempArray[p] = new Haplotype(genos, tempPerc, preFiltBlock); p++; } } //make the results array only large enough to hold haps //which pass threshold above results[k] = new Haplotype[p]; for (int z = 0; z < p; z++){ results[k][z] = tempArray[z]; } } return results; }
hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMinor()));
if (Chromosome.getFilteredMarker(selectedMarkers[currentClass]).getMajor() == genos[indexIntoBlock]){ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMajor())); }else{ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMinor())); }
Haplotype[][] generateHaplotypes(Vector blocks, int hapthresh) throws HaploViewException{ //TODO: output indiv hap estimates Haplotype[][] results = new Haplotype[blocks.size()][]; //String raw = new String(); //String currentLine; this.totalBlocks = blocks.size(); this.blocksDone = 0; for (int k = 0; k < blocks.size(); k++){ this.blocksDone++; int[] preFiltBlock = (int[])blocks.elementAt(k); int[] theBlock; int[] selectedMarkers = new int[0]; int[] equivClass = new int[0]; if (preFiltBlock.length > 30){ equivClass = new int[preFiltBlock.length]; int classCounter = 0; for (int x = 0; x < preFiltBlock.length; x++){ int marker1 = preFiltBlock[x]; //already been lumped into an equivalency class if (equivClass[x] != 0){ continue; } //start a new equivalency class for this SNP classCounter ++; equivClass[x] = classCounter; for (int y = x+1; y < preFiltBlock.length; y++){ int marker2 = preFiltBlock[y]; if (marker1 > marker2){ int tmp = marker1; marker1 = marker2; marker2 = tmp; } if (filteredDPrimeTable[marker1][marker2].getRSquared() == 1.0){ //these two SNPs are redundant equivClass[y] = classCounter; } } } //parse equivalency classes selectedMarkers = new int[classCounter]; for (int x = 0; x < selectedMarkers.length; x++){ selectedMarkers[x] = -1; } for (int x = 0; x < classCounter; x++){ double genoPC = 1.0; for (int y = 0; y < equivClass.length; y++){ if (equivClass[y] == x+1){ //int[]tossed = new int[3]; if (percentBadGenotypes[preFiltBlock[y]] < genoPC){ selectedMarkers[x] = preFiltBlock[y]; genoPC = percentBadGenotypes[preFiltBlock[y]]; } } } } theBlock = selectedMarkers; Arrays.sort(theBlock); //System.out.println("Block " + k + " " + theBlock.length + "/" + preFiltBlock.length); }else{ theBlock = preFiltBlock; } //break up large blocks if needed int[] block_size; if (theBlock.length < 9){ block_size = new int[1]; block_size[0] = theBlock.length; } else { //some base-8 arithmetic int ones = theBlock.length%8; int eights = (theBlock.length - ones)/8; if (ones == 0){ block_size = new int[eights]; for (int i = 0; i < eights; i++){ block_size[i]=8; } } else { block_size = new int[eights+1]; for (int i = 0; i < eights-1; i++){ block_size[i]=8; } block_size[eights-1] = (8+ones)/2; block_size[eights] = 8+ones-block_size[eights-1]; } } byte[] thisHap; Vector inputHaploVector = new Vector(); for (int i = 0; i < chromosomes.size(); i++){ thisHap = new byte[theBlock.length]; Chromosome thisChrom = (Chromosome)chromosomes.elementAt(i); Chromosome nextChrom = (Chromosome)chromosomes.elementAt(++i); boolean tooManyMissingInASegment = false; int totalMissing = 0; int segmentShift = 0; for (int n = 0; n < block_size.length; n++){ int missing = 0; for (int j = 0; j < block_size[n]; j++){ byte theGeno = thisChrom.getFilteredGenotype(theBlock[segmentShift+j]); byte nextGeno = nextChrom.getFilteredGenotype(theBlock[segmentShift+j]); if(theGeno == 0 || nextGeno == 0) missing++; } segmentShift += block_size[n]; if (missing >= missingLimit){ tooManyMissingInASegment = true; } totalMissing += missing; } //we want to use chromosomes without too many missing genotypes in a given //subsegment (first term) or without too many missing genotypes in the //whole block (second term) if (!tooManyMissingInASegment && totalMissing <= 1+theBlock.length/3){ for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); byte theGeno = thisChrom.getFilteredGenotype(theBlock[j]); if (theGeno >= 5){ thisHap[j] = 'h'; } else { if (theGeno == a1){ thisHap[j] = '1'; }else if (theGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } inputHaploVector.add(thisHap); thisHap = new byte[theBlock.length]; for (int j = 0; j < theBlock.length; j++){ byte a1 = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); byte a2 = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); byte nextGeno = nextChrom.getFilteredGenotype(theBlock[j]); if (nextGeno >= 5){ thisHap[j] = 'h'; } else { if (nextGeno == a1){ thisHap[j] = '1'; }else if (nextGeno == a2){ thisHap[j] = '2'; }else{ thisHap[j] = '0'; } } } inputHaploVector.add(thisHap); } } byte[][] input_haplos = (byte[][])inputHaploVector.toArray(new byte[0][0]); String EMreturn = new String(""); int[] num_haplos_present = new int[1]; Vector haplos_present = new Vector(); Vector haplo_freq = new Vector(); //kirby patch EM theEM = new EM(); theEM.full_em_breakup(input_haplos, 4, num_haplos_present, haplos_present, haplo_freq, block_size, 0); for (int j = 0; j < haplos_present.size(); j++){ EMreturn += (String)haplos_present.elementAt(j)+"\t"+(String)haplo_freq.elementAt(j)+"\t"; } StringTokenizer st = new StringTokenizer(EMreturn); int p = 0; Haplotype[] tempArray = new Haplotype[st.countTokens()/2]; while(st.hasMoreTokens()){ String aString = st.nextToken(); int[] genos = new int[aString.length()]; for (int j = 0; j < aString.length(); j++){ byte returnBit = Byte.parseByte(aString.substring(j,j+1)); if (returnBit == 1){ genos[j] = Chromosome.getFilteredMarker(theBlock[j]).getMajor(); }else{ if (Chromosome.getFilteredMarker(theBlock[j]).getMinor() == 0){ genos[j] = 8; }else{ genos[j] = Chromosome.getFilteredMarker(theBlock[j]).getMinor(); } } } if (selectedMarkers.length > 0){ //we need to reassemble the haplotypes Hashtable hapsHash = new Hashtable(); //add to hash all the genotypes we phased for (int q = 0; q < genos.length; q++){ hapsHash.put(new Integer(theBlock[q]), new Integer(genos[q])); } //now add all the genotypes we didn't bother phasing, based on //which marker they are identical to for (int q = 0; q < equivClass.length; q++){ int currentClass = equivClass[q]-1; if (selectedMarkers[currentClass] == preFiltBlock[q]){ //we alredy added the phased genotypes above continue; } int indexIntoBlock=0; for (int x = 0; x < theBlock.length; x++){ if (theBlock[x] == selectedMarkers[currentClass]){ indexIntoBlock = x; break; } } //this (somewhat laboriously) reconstructs whether to add the minor or major allele if (Chromosome.getFilteredMarker(selectedMarkers[currentClass]).getMajor() == genos[indexIntoBlock]){ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMajor())); }else{ hapsHash.put(new Integer(preFiltBlock[q]), new Integer(Chromosome.getFilteredMarker(preFiltBlock[q]).getMinor())); } } genos = new int[preFiltBlock.length]; for (int q = 0; q < preFiltBlock.length; q++){ genos[q] = ((Integer)hapsHash.get(new Integer(preFiltBlock[q]))).intValue(); } } double tempPerc = Double.parseDouble(st.nextToken()); if (tempPerc*100 > hapthresh){ tempArray[p] = new Haplotype(genos, tempPerc, preFiltBlock); p++; } } //make the results array only large enough to hold haps //which pass threshold above results[k] = new Haplotype[p]; for (int z = 0; z < p; z++){ results[k][z] = tempArray[z]; } } return results; }
HaplotypeAssociationNode curHap = (HaplotypeAssociationNode) ham.getChild(curBlock,i);
HaplotypeAssociationNode curHap = (HaplotypeAssociationNode) ham.getChild(curBlock,j);
void export(int tabNum, int format, int start, int stop){ fc.setSelectedFile(new File("")); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){ File outfile = fc.getSelectedFile(); if (format == PNG_MODE || format == COMPRESSED_PNG_MODE){ BufferedImage image = null; if (tabNum == VIEW_D_NUM){ try { if (format == PNG_MODE){ image = dPrimeDisplay.export(start, stop, false); }else{ image = dPrimeDisplay.export(start, stop, true); } } catch(HaploViewException hve) { JOptionPane.showMessageDialog(this, hve.getMessage(), "Export Error", JOptionPane.ERROR_MESSAGE); } }else if (tabNum == VIEW_HAP_NUM){ image = hapDisplay.export(); }else{ image = new BufferedImage(1,1,BufferedImage.TYPE_3BYTE_BGR); } try{ String filename = outfile.getPath(); if (! (filename.endsWith(".png") || filename.endsWith(".PNG"))){ filename += ".png"; } Jimi.putImage("image/png", image, filename); }catch(JimiException je){ JOptionPane.showMessageDialog(this, je.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } else if (format == TXT_MODE){ try{ if (tabNum == VIEW_D_NUM){ theData.saveDprimeToText(outfile, TABLE_TYPE, start, stop); }else if (tabNum == VIEW_HAP_NUM){ theData.saveHapsToText(hapDisplay.filteredHaplos,hapDisplay.multidprimeArray, outfile); }else if (tabNum == VIEW_CHECK_NUM){ checkPanel.printTable(outfile); }else if (tabNum == VIEW_TDT_NUM){ JTable table = tdtPanel.getTable(); JTreeTable jtt = ((HaploAssocPanel)((JTabbedPane)tabs.getComponent(tabNum)). getComponent(1)).jtt; FileWriter assocWriter = new FileWriter(outfile); int numCols = table.getColumnCount(); StringBuffer header = new StringBuffer("Single Marker Association\n"); for (int i = 0; i < numCols; i++){ header.append(table.getColumnName(i)).append("\t"); } header.append("\n"); assocWriter.write(header.toString()); for (int i = 0; i < table.getRowCount(); i++){ StringBuffer sb = new StringBuffer(); for (int j = 0; j < numCols; j++){ sb.append(table.getValueAt(i,j)).append("\t"); } sb.append("\n"); assocWriter.write(sb.toString()); } //now we write the haplotype association numCols = jtt.getColumnCount(); header = new StringBuffer("\nHaplotype Association\n\t"); for (int i = 0; i < numCols; i++){ header.append(jtt.getColumnName(i)).append("\t"); } header.append("\n"); assocWriter.write(header.toString()); HaplotypeAssociationModel ham = (HaplotypeAssociationModel) jtt.getTree().getModel(); HaplotypeAssociationNode root = (HaplotypeAssociationNode) ham.getRoot(); for(int i=0;i<ham.getChildCount(root);i++) { HaplotypeAssociationNode curBlock = (HaplotypeAssociationNode) ham.getChild(root,i); assocWriter.write(curBlock.getName() + "\n"); StringBuffer sb = new StringBuffer(); for(int j=0;j<ham.getChildCount(curBlock);j++){ HaplotypeAssociationNode curHap = (HaplotypeAssociationNode) ham.getChild(curBlock,i); sb.append("\t").append(curHap.getName()).append("\t"); sb.append(curHap.getFreq()).append("\t"); sb.append(curHap.getCounts()).append("\t"); sb.append(curHap.getChiSq()).append("\t"); sb.append(curHap.getPVal()).append("\n"); } assocWriter.write(sb.toString()); } assocWriter.close(); } }catch(IOException ioe){ JOptionPane.showMessageDialog(this, ioe.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } }
theBlocks.add(thisBlock);
if (thisBlock.length > 1){ theBlocks.add(thisBlock); }
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(); } int count = 0; for (int i = 0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ count++; } } Chromosome.realIndex = new int[count]; int k = 0; for (int i =0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ Chromosome.realIndex[k] = i; k++; } } theData.filteredDPrimeTable = theData.getFilteredTable(); //after editing the filtered marker list, needs to be prodded into //resizing correctly Dimension size = dPrimeDisplay.getSize(); Dimension pref = dPrimeDisplay.getPreferredSize(); Rectangle visRect = dPrimeDisplay.getVisibleRect(); if (size.width != pref.width && pref.width > visRect.width){ ((JViewport)dPrimeDisplay.getParent()).setViewSize(pref); } 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(); } 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; } }
chroms.add(new Chromosome(ped, indiv, genos, false, infile.getName()));
chroms.add(new Chromosome(ped, indiv, genos, infile.getName()));
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.hasMoreTokens()){ ped = st.nextToken(); indiv = st.nextToken(); }else{ throw new HaploViewException("Genotype file error:\nLine " + lineCount + " appears to have fewer than 2 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, false, infile.getName())); } 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; //initialize realIndex Chromosome.doFilter(genos.length); //wipe clean any existing marker info so we know we're starting clean with a new file Chromosome.markers = null; }
r.repaint();
protected void doCreateRelationship() { try { Relationship r = new Relationship(pp, pkTable, fkTable); pp.add(r); } catch (ArchitectException ex) { logger.error("Couldn't create relationship", ex); JOptionPane.showMessageDialog(pp, "Couldn't create relationship: "+ex.getMessage()); } }
int high = V_BORDER+2 + count*BOX_SIZE/2;
int high = 2*V_BORDER + count*BOX_SIZE/2;
public Dimension getPreferredSize() { int count = dPrimeTable.length; int high = V_BORDER+2 + count*BOX_SIZE/2; if (markersLoaded){ high += TICK_BOTTOM + widestMarkerName + TEXT_NUMBER_GAP; } return new Dimension(H_BORDER+2 + BOX_SIZE*(count-1), high); }
return new Dimension(H_BORDER+2 + BOX_SIZE*(count-1), high);
return new Dimension(2*H_BORDER + BOX_SIZE*(count-1), high);
public Dimension getPreferredSize() { int count = dPrimeTable.length; int high = V_BORDER+2 + count*BOX_SIZE/2; if (markersLoaded){ high += TICK_BOTTOM + widestMarkerName + TEXT_NUMBER_GAP; } return new Dimension(H_BORDER+2 + BOX_SIZE*(count-1), high); }
gComponent2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2);
if (!(markersLoaded)){ gComponent2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { gComponent2.translate((size.width - pref.width) / 2, 0); }
public void paintComponent(Graphics gComponent){ Dimension size = getSize(); Dimension pref = getPreferredSize(); if (!(alreadyPainted)){ buffIm = new BufferedImage(pref.width, pref.height, BufferedImage.TYPE_3BYTE_BGR); Graphics g = buffIm.getGraphics(); FontMetrics boxFontMetrics = g.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; int left = H_BORDER; int top = V_BORDER; FontMetrics metrics; int ascent; Graphics2D g2 = (Graphics2D) g; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); if (markersLoaded) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.25f); int wide = dPrimeTable.length * BOX_SIZE; int lineLeft = wide / 4; int lineSpan = wide / 2; long minpos = ((SNP)markers.elementAt(0)).getPosition(); long maxpos = ((SNP)markers.elementAt(markers.size()-1)).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < markers.size(); i++) { double pos = (((SNP)markers.elementAt(i)).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g.drawLine(xx, 5 + TICK_HEIGHT, left + i*BOX_SIZE, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names g.setFont(markerNameFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); widestMarkerName = metrics.stringWidth(((SNP)markers.elementAt(0)).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(((SNP)markers.elementAt(x)).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } //System.out.println(widest); g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); TextLayout markerNameTL; for (int x = 0; x < dPrimeTable.length; x++) { g2.drawString(((SNP)markers.elementAt(x)).getName(),TEXT_NUMBER_GAP, x*BOX_SIZE + ascent/3); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_NUMBER_GAP; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } //// draw the marker numbers g.setFont(markerNumFont); metrics = g.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(x + 1); g.drawString(mark, left + x*BOX_SIZE - metrics.stringWidth(mark)/2, top + ascent); } top += BOX_RADIUS/2; // give a little space between numbers and boxes // draw table column by column for (int x = 0; x < dPrimeTable.length-1; x++) { for (int y = x + 1; y < dPrimeTable.length; y++) { double d = dPrimeTable[x][y].getDPrime(); double l = dPrimeTable[x][y].getLOD(); Color boxColor = dPrimeTable[x][y].getColor(); // draw markers above int rt2 = (int) (Math.sqrt(2) * (double)BOX_SIZE); //int rt2half = (int) (0.5 * Math.sqrt(2) * (double)BOX_SIZE); int rt2half = rt2 / 2; //System.out.println(rt2 + " " + rt2half); //int xx = left + x*BOX_SIZE + (int) (y*Math.sqrt(4)*BOX_SIZE*0.5); int xx = left + (x + y) * BOX_SIZE / 2; //int yy = top + (x - y) * BOX_SIZE; //int xx = left + x*BOX_SIZE; //int yy = top + y*BOX_SIZE - (int) (x*Math.sqrt(4)*BOX_SIZE*0.5); int yy = top + (y - x) * BOX_SIZE / 2; diamondX[0] = xx; diamondY[0] = yy - BOX_RADIUS; diamondX[1] = xx + BOX_RADIUS; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + BOX_RADIUS; diamondX[3] = xx - BOX_RADIUS; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g.setColor(boxColor); g.fillPolygon(diamond); if (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.lightGray); g.drawPolygon(diamond); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } g.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } alreadyPainted=true; } Graphics2D gComponent2 = (Graphics2D)gComponent; gComponent2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); gComponent2.drawImage(buffIm,0,0,this); }
return;
logger.debug("SQLRelationship: populate is a no-op");
public void populate() throws ArchitectException { return; }
checkSystem();
void run() { PhotovaultSettings settings = PhotovaultSettings.getSettings(); Collection databases = settings.getDatabases(); if ( databases.size() == 0 ) { DbSettingsDlg dlg = new DbSettingsDlg( null, true ); if ( dlg.showDialog() != dlg.APPROVE_OPTION ) { System.exit( 0 ); } } LoginDlg login = new LoginDlg( this ); boolean loginOK = false; while ( !loginOK ) { int retval = login.showDialog(); switch( retval ) { case LoginDlg.RETURN_REASON_CANCEL: System.exit( 0 ); break; case LoginDlg.RETURN_REASON_NEWDB: DbSettingsDlg dlg = new DbSettingsDlg( null, true ); if ( dlg.showDialog() == dlg.APPROVE_OPTION ) { login = new LoginDlg( this ); } break; case LoginDlg.RETURN_REASON_APPROVE: if ( login( login ) ) { loginOK = true; BrowserWindow wnd = new BrowserWindow(); } else { JOptionPane.showMessageDialog( null, "Error logging into Photovault", "Login error", JOptionPane.ERROR_MESSAGE ); } break; default: log.error( "Unknown return code form LoginDlg.showDialog(): " + retval ); break; } } }
fail( getBodyText(), "evaluating test: "+ test );
fail( getBodyText(), "evaluating test: "+ test.getExpressionText() );
public void doTag(XMLOutput output) throws Exception { if (test == null && xpath == null) { throw new MissingAttributeException( "test" ); } if (test != null) { if (! test.evaluateAsBoolean(context)) { fail( getBodyText(), "evaluating test: "+ test ); } } else { Object xpathContext = getXPathContext(); if (! xpath.booleanValueOf(xpathContext)) { fail( getBodyText(), "evaluating xpath: "+ xpath ); } } }
r1.paint((Graphics2D) pp.getGraphics()); r2.paint((Graphics2D) pp.getGraphics());
public void testNoCrossingLinesEasy() throws ArchitectException { PlayPen pp = layoutAction.getPlayPen(); SQLDatabase ppdb = pp.getDatabase(); SQLTable tables[] = new SQLTable[4]; TablePane tablePanes[] = new TablePane[tables.length]; for (int i = 0; i < tables.length; i++) { tables[i] = new SQLTable(ppdb, "Table "+i, "", "TABLE", true); tablePanes[i] = new TablePane(tables[i], pp); } pp.addTablePane(tablePanes[0], new Point(100, 0)); pp.addTablePane(tablePanes[1], new Point(300, 100)); pp.addTablePane(tablePanes[2], new Point(150, 200)); pp.addTablePane(tablePanes[3], new Point(0, 100)); SQLRelationship sr1 = new SQLRelationship(); sr1.attachRelationship(tables[0],tables[2],false); SQLRelationship sr2 = new SQLRelationship(); sr2.attachRelationship(tables[1],tables[3],false); pp.setVisible(true); Relationship r1 = new Relationship(pp, sr1); Relationship r2 = new Relationship(pp, sr2); pp.addRelationship(r1); pp.addRelationship(r2); // the relationships init their paths only when painted r1.paint((Graphics2D) pp.getGraphics()); r2.paint((Graphics2D) pp.getGraphics()); // check that the relationships start out crossed assertTrue(((RelationshipUI) r1.getUI()).intersectsShape(((RelationshipUI) r2.getUI()).getShape())); // check that neither of the relationships intersects any of the 4 tables to start Rectangle b = new Rectangle(); for (int i = 0; i < tablePanes.length; i++) { tablePanes[i].getBounds(b); if (tablePanes[i] != r1.getPkTable() && tablePanes[i] != r1.getFkTable()) { assertFalse("Table "+i+" crosses r1", ((RelationshipUI) r1.getUI()).intersects(b)); } if (tablePanes[i] != r2.getPkTable() && tablePanes[i] != r2.getFkTable()) { assertFalse("Table "+i+" crosses r2", ((RelationshipUI) r2.getUI()).intersects(b)); } } layoutAction.actionPerformed(new ActionEvent(this, 0, null)); // make the paths update r1.paint((Graphics2D) pp.getGraphics()); r2.paint((Graphics2D) pp.getGraphics()); // check that the relationships are uncrossed assertFalse(((RelationshipUI) r1.getUI()).intersectsShape(((RelationshipUI) r2.getUI()).getShape())); // check that neither of the relationships intersects any of the 4 tables to start for (int i = 0; i < tablePanes.length; i++) { tablePanes[i].getBounds(b); if (tablePanes[i] != r1.getPkTable() && tablePanes[i] != r1.getFkTable()) { assertFalse("Table "+i+" crosses r1", ((RelationshipUI) r1.getUI()).intersects(b)); } if (tablePanes[i] != r2.getPkTable() && tablePanes[i] != r2.getFkTable()) { assertFalse("Table "+i+" crosses r2", ((RelationshipUI) r2.getUI()).intersects(b)); } } }
r1.paint((Graphics2D) pp.getGraphics()); r2.paint((Graphics2D) pp.getGraphics());
r1.paint(g); r2.paint(g); g.dispose();
public void testNoCrossingLinesEasy() throws ArchitectException { PlayPen pp = layoutAction.getPlayPen(); SQLDatabase ppdb = pp.getDatabase(); SQLTable tables[] = new SQLTable[4]; TablePane tablePanes[] = new TablePane[tables.length]; for (int i = 0; i < tables.length; i++) { tables[i] = new SQLTable(ppdb, "Table "+i, "", "TABLE", true); tablePanes[i] = new TablePane(tables[i], pp); } pp.addTablePane(tablePanes[0], new Point(100, 0)); pp.addTablePane(tablePanes[1], new Point(300, 100)); pp.addTablePane(tablePanes[2], new Point(150, 200)); pp.addTablePane(tablePanes[3], new Point(0, 100)); SQLRelationship sr1 = new SQLRelationship(); sr1.attachRelationship(tables[0],tables[2],false); SQLRelationship sr2 = new SQLRelationship(); sr2.attachRelationship(tables[1],tables[3],false); pp.setVisible(true); Relationship r1 = new Relationship(pp, sr1); Relationship r2 = new Relationship(pp, sr2); pp.addRelationship(r1); pp.addRelationship(r2); // the relationships init their paths only when painted r1.paint((Graphics2D) pp.getGraphics()); r2.paint((Graphics2D) pp.getGraphics()); // check that the relationships start out crossed assertTrue(((RelationshipUI) r1.getUI()).intersectsShape(((RelationshipUI) r2.getUI()).getShape())); // check that neither of the relationships intersects any of the 4 tables to start Rectangle b = new Rectangle(); for (int i = 0; i < tablePanes.length; i++) { tablePanes[i].getBounds(b); if (tablePanes[i] != r1.getPkTable() && tablePanes[i] != r1.getFkTable()) { assertFalse("Table "+i+" crosses r1", ((RelationshipUI) r1.getUI()).intersects(b)); } if (tablePanes[i] != r2.getPkTable() && tablePanes[i] != r2.getFkTable()) { assertFalse("Table "+i+" crosses r2", ((RelationshipUI) r2.getUI()).intersects(b)); } } layoutAction.actionPerformed(new ActionEvent(this, 0, null)); // make the paths update r1.paint((Graphics2D) pp.getGraphics()); r2.paint((Graphics2D) pp.getGraphics()); // check that the relationships are uncrossed assertFalse(((RelationshipUI) r1.getUI()).intersectsShape(((RelationshipUI) r2.getUI()).getShape())); // check that neither of the relationships intersects any of the 4 tables to start for (int i = 0; i < tablePanes.length; i++) { tablePanes[i].getBounds(b); if (tablePanes[i] != r1.getPkTable() && tablePanes[i] != r1.getFkTable()) { assertFalse("Table "+i+" crosses r1", ((RelationshipUI) r1.getUI()).intersects(b)); } if (tablePanes[i] != r2.getPkTable() && tablePanes[i] != r2.getFkTable()) { assertFalse("Table "+i+" crosses r2", ((RelationshipUI) r2.getUI()).intersects(b)); } } }
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
public TDTPanel(PedFile pf) throws PedFileException{ if (Options.getAssocTest() == ASSOC_TRIO){ result = TDT.calcTrioTDT(pf); }else{ result = TDT.calcCCTDT(pf); } tableColumnNames.add("#"); tableColumnNames.add("Name"); if (Options.getAssocTest() == ASSOC_TRIO){ tableColumnNames.add("Overtransmitted"); tableColumnNames.add("T:U"); }else{ tableColumnNames.add("Major Alleles"); tableColumnNames.add("Case, Control Ratios"); } tableColumnNames.add("Chi Squared"); tableColumnNames.add("p value"); refreshTable(); }
tempVect.add(currentResult.getTURatio(Options.getAssocTest()));
if(this.countsOrFreqs == SHOW_SINGLE_FREQS) { tempVect.add(currentResult.getFreqs(Options.getAssocTest())); } else if (this.countsOrFreqs == SHOW_SINGLE_COUNTS) { tempVect.add(currentResult.getTURatio(Options.getAssocTest())); }
public void refreshTable(){ this.removeAll(); Vector tableData = new Vector(); int numRes = Chromosome.getSize(); for (int i = 0; i < numRes; i++){ Vector tempVect = new Vector(); TDTResult currentResult = (TDTResult)result.get(Chromosome.realIndex[i]); tempVect.add(new Integer(Chromosome.realIndex[i]+1)); tempVect.add(currentResult.getName()); tempVect.add(currentResult.getOverTransmittedAllele(Options.getAssocTest())); tempVect.add(currentResult.getTURatio(Options.getAssocTest())); tempVect.add(new Double(currentResult.getChiSq(Options.getAssocTest()))); tempVect.add(currentResult.getPValue()); tableData.add(tempVect.clone()); } TDTTableModel tm = new TDTTableModel(tableColumnNames, tableData); table = new JTable(tm); table.getColumnModel().getColumn(0).setPreferredWidth(50); table.getColumnModel().getColumn(1).setPreferredWidth(100); if (Options.getAssocTest() != ASSOC_TRIO){ table.getColumnModel().getColumn(3).setPreferredWidth(160); } table.getColumnModel().getColumn(2).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); }
if(Options.getAssocTest() == ASSOC_CC) { JRadioButton countsButton = new JRadioButton("Show CC counts"); JRadioButton ratiosButton = new JRadioButton("Show CC frequencies"); ButtonGroup bg = new ButtonGroup(); bg.add(countsButton); bg.add(ratiosButton); countsButton.addActionListener(this); ratiosButton.addActionListener(this); JPanel buttPan = new JPanel(); buttPan.add(countsButton); buttPan.add(ratiosButton); add(buttPan); if(countsOrFreqs == SHOW_SINGLE_FREQS) { ratiosButton.setSelected(true); }else{ countsButton.setSelected(true); } }
public void refreshTable(){ this.removeAll(); Vector tableData = new Vector(); int numRes = Chromosome.getSize(); for (int i = 0; i < numRes; i++){ Vector tempVect = new Vector(); TDTResult currentResult = (TDTResult)result.get(Chromosome.realIndex[i]); tempVect.add(new Integer(Chromosome.realIndex[i]+1)); tempVect.add(currentResult.getName()); tempVect.add(currentResult.getOverTransmittedAllele(Options.getAssocTest())); tempVect.add(currentResult.getTURatio(Options.getAssocTest())); tempVect.add(new Double(currentResult.getChiSq(Options.getAssocTest()))); tempVect.add(currentResult.getPValue()); tableData.add(tempVect.clone()); } TDTTableModel tm = new TDTTableModel(tableColumnNames, tableData); table = new JTable(tm); table.getColumnModel().getColumn(0).setPreferredWidth(50); table.getColumnModel().getColumn(1).setPreferredWidth(100); if (Options.getAssocTest() != ASSOC_TRIO){ table.getColumnModel().getColumn(3).setPreferredWidth(160); } table.getColumnModel().getColumn(2).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); }
if (fam.getMember(ind.getIndividualID()) != null){
if (fam.getMembers().containsKey(ind.getIndividualID())){
public void parseLinkage(Vector pedigrees) throws PedFileException { int colNum = -1; boolean withOptionalColumn = false; int numLines = pedigrees.size(); Individual ind; this.order = new Vector(); for(int k=0; k<numLines; k++){ StringTokenizer tokenizer = new StringTokenizer((String)pedigrees.get(k), "\n\t\" \""); //reading the first line if(colNum < 1){ //only check column number count for the first nonblank line colNum = tokenizer.countTokens(); if(colNum%2==1) { withOptionalColumn = true; } } if(colNum != tokenizer.countTokens()) { //this line has a different number of columns //should send some sort of error message //TODO: add something which stores number of markers for all lines and checks that they're consistent throw new PedFileException("Line number mismatch in pedfile. line " + (k+1)); } ind = new Individual(tokenizer.countTokens()); if(tokenizer.countTokens() < 6) { throw new PedFileException("Incorrect number of fields on line " + (k+1)); } if(tokenizer.hasMoreTokens()){ ind.setFamilyID(tokenizer.nextToken().trim()); ind.setIndividualID(tokenizer.nextToken().trim()); ind.setDadID(tokenizer.nextToken().trim()); ind.setMomID(tokenizer.nextToken().trim()); try { //TODO: affected/liability should not be forced into Integers! ind.setGender(Integer.parseInt(tokenizer.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(tokenizer.nextToken().trim())); if(withOptionalColumn) { ind.setLiability(Integer.parseInt(tokenizer.nextToken().trim())); } }catch(NumberFormatException nfe) { throw new PedFileException("Pedfile error: invalid gender or affected status on line " + (k+1)); } while(tokenizer.hasMoreTokens()){ try { int allele1 = Integer.parseInt(tokenizer.nextToken().trim()); int allele2 = Integer.parseInt(tokenizer.nextToken().trim()); if(allele1 <0 || allele1 > 4 || allele2 <0 || allele2 >4) { throw new PedFileException("Pedigree file input error: invalid genotype on line " + (k+1) + ".\n all genotypes must be 0-4."); } byte[] markers = new byte[2]; markers[0] = (byte)allele1; markers[1]= (byte)allele2; ind.addMarker(markers); }catch(NumberFormatException nfe) { throw new PedFileException("Pedigree file input error: invalid genotype on line " + (k+1) ); } } //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()); } if (fam.getMember(ind.getIndividualID()) != null){ throw new PedFileException("Individual "+ind.getIndividualID()+" in family "+ ind.getFamilyID()+" appears more than once."); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); String[] indFamID = new String[2]; indFamID[0] = ind.getFamilyID(); indFamID[1] = ind.getIndividualID(); this.order.add(ind); } } //now we check if anyone has a reference to a parent who isnt in the file, and if so, we remove the reference for(int i=0;i<order.size();i++) { Individual currentInd = (Individual) order.get(i); Hashtable curFam = ((Family)(families.get(currentInd.getFamilyID())) ).getMembers(); if( !currentInd.getDadID().equals("0") && ! (curFam.containsKey(currentInd.getDadID()))) { currentInd.setDadID("0"); bogusParents = true; } if(!currentInd.getMomID().equals("0") && ! (curFam.containsKey(currentInd.getMomID()))) { currentInd.setMomID("0"); bogusParents = true; } } }
if (stylesheet instanceof JellyStylesheet) { JellyStylesheet jellyStyle = (JellyStylesheet) stylesheet; jellyStyle.setOutput(output); }
public void doTag(XMLOutput output) throws Exception { Stylesheet stylesheet = getStylesheet(); if (stylesheet == null) { throw new MissingAttributeException("stylesheet"); } Object source = getSource(); if (log.isDebugEnabled()) { log.debug("About to evaluate stylesheet on source: " + source); } stylesheet.run(source); }
if (info[4].equals("")){
if (info[3].equals("")){
public void parsePhasedData(String[] info) throws IOException, PedFileException{ if (info[4].equals("")){ Chromosome.setDataChrom("none"); }else{ Chromosome.setDataChrom("chr" + info[4]); } Chromosome.setDataBuild("ncbi_b35"); Vector sampleData = new Vector(); Vector legendData = new Vector(); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); File phasedFile = new File(info[0]); File sampleFile = new File(info[1]); File legendFile = new File(info[2]); if (phasedFile.length() < 1){ throw new PedFileException("Genotypes file is empty or non-existent: " + phasedFile.getName()); }else if (sampleFile.length() < 1){ throw new PedFileException("Sample file is empty or non-existent: " + sampleFile.getName()); }else if (legendFile.length() < 1){ throw new PedFileException("Legend file is empty or non-existent: " + legendFile.getName()); } //read in the individual ids data. try{ BufferedReader sampleBuffReader; if (Options.getGzip()){ FileInputStream sampleFis = new FileInputStream(sampleFile); GZIPInputStream sampleInputStream = new GZIPInputStream(sampleFis); sampleBuffReader = new BufferedReader(new InputStreamReader(sampleInputStream)); }else{ FileReader sampleReader = new FileReader(sampleFile); sampleBuffReader = new BufferedReader(sampleReader); } String sampleLine; while((sampleLine = sampleBuffReader.readLine())!=null){ StringTokenizer sampleTokenizer = new StringTokenizer(sampleLine); sampleData.add(sampleTokenizer.nextToken()); } }catch(NoSuchElementException nse){ throw new PedFileException("File format error: " + sampleFile.getName()); } //read in the legend data try{ BufferedReader legendBuffReader; if (Options.getGzip()){ FileInputStream legendFis = new FileInputStream(legendFile); GZIPInputStream legendInputStream = new GZIPInputStream(legendFis); legendBuffReader = new BufferedReader(new InputStreamReader(legendInputStream)); }else{ FileReader legendReader = new FileReader(legendFile); legendBuffReader = new BufferedReader(legendReader); } String legendLine; String zero, one; while((legendLine = legendBuffReader.readLine())!=null){ StringTokenizer legendSt = new StringTokenizer(legendLine); String markerid = legendSt.nextToken(); if (markerid.equalsIgnoreCase("rs") || markerid.equalsIgnoreCase("marker")){ //skip header continue; } legendMarkers.add(markerid); legendPositions.add(legendSt.nextToken()); byte[] legendBytes = new byte[2]; zero = legendSt.nextToken(); one = legendSt.nextToken(); if (zero.equalsIgnoreCase("A")){ legendBytes[0] = 1; }else if (zero.equalsIgnoreCase("C")){ legendBytes[0] = 2; }else if (zero.equalsIgnoreCase("G")){ legendBytes[0] = 3; }else if (zero.equalsIgnoreCase("T")){ legendBytes[0] = 4; }else{ throw new PedFileException("Invalid allele: " + zero); } if (one.equalsIgnoreCase("A")){ legendBytes[1] = 1; }else if (one.equalsIgnoreCase("C")){ legendBytes[1] = 2; }else if (one.equalsIgnoreCase("G")){ legendBytes[1] = 3; }else if (one.equalsIgnoreCase("T")){ legendBytes[1] = 4; }else{ throw new PedFileException("Invalid allele: " + one); } legendData.add(legendBytes); } 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); } }catch(NoSuchElementException nse){ throw new PedFileException("File format error: " + legendFile.getName()); } //read in the phased data. try{ BufferedReader phasedBuffReader; if (Options.getGzip()){ FileInputStream phasedFis = new FileInputStream(phasedFile); GZIPInputStream phasedInputStream = new GZIPInputStream(phasedFis); phasedBuffReader = new BufferedReader(new InputStreamReader(phasedInputStream)); }else{ FileReader phasedReader = new FileReader(phasedFile); phasedBuffReader = new BufferedReader(phasedReader); } String phasedLine; int columns = 0; String token; boolean even = false; int iterator = 0; while((phasedLine = phasedBuffReader.readLine()) != null){ StringTokenizer phasedSt = new StringTokenizer(phasedLine); columns = phasedSt.countTokens(); if(even){ iterator++; }else{ //Only set up a new individual every 2 lines. ind = new Individual(columns, true); try{ ind.setIndividualID((String)sampleData.get(iterator)); }catch (ArrayIndexOutOfBoundsException e){ throw new PedFileException("File error: Sample file is missing individual IDs"); } if (columns != legendData.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); //exception in case of wierd compression combos in input files if (details == null){ throw new PedFileException("File format error: " + sampleFile.getName()); } 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()); } //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 (!even){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } while(phasedSt.hasMoreTokens()){ token = phasedSt.nextToken(); if (!even){ if (token.equalsIgnoreCase("0")){ byteDataT[index] = ((byte[])legendData.get(index))[0]; }else if (token.equalsIgnoreCase("1")){ byteDataT[index] = ((byte[])legendData.get(index))[1]; }else { throw new PedFileException("File format error: " + phasedFile.getName()); } }else{ if (token.equalsIgnoreCase("0")){ byteDataU[index] = ((byte[])legendData.get(index))[0]; }else if (token.equalsIgnoreCase("1")){ byteDataU[index] = ((byte[])legendData.get(index))[1]; }else if (Chromosome.getDataChrom().equalsIgnoreCase("chrx") && ind.getGender() == Individual.MALE && token.equalsIgnoreCase("-")){ //X male }else { throw new PedFileException("File format error: " + phasedFile.getName()); } } index++; } if (even){ if (ind.getGender() == Individual.MALE && Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ for(int i=0; i < columns; i++){ ind.addMarker(byteDataT[i], byteDataT[i]); } }else{ for(int i=0; i < columns; i++){ ind.addMarker(byteDataT[i], byteDataU[i]); } } } even = !even; } }catch(NoSuchElementException nse){ throw new PedFileException("File format error: " + phasedFile.getName()); } }
Chromosome.setDataChrom("chr" + info[4]);
Chromosome.setDataChrom("chr" + info[3]);
public void parsePhasedData(String[] info) throws IOException, PedFileException{ if (info[4].equals("")){ Chromosome.setDataChrom("none"); }else{ Chromosome.setDataChrom("chr" + info[4]); } Chromosome.setDataBuild("ncbi_b35"); Vector sampleData = new Vector(); Vector legendData = new Vector(); Vector legendMarkers = new Vector(); Vector legendPositions = new Vector(); Individual ind = null; byte[] byteDataT = new byte[0]; byte[] byteDataU = new byte[0]; this.allIndividuals = new Vector(); File phasedFile = new File(info[0]); File sampleFile = new File(info[1]); File legendFile = new File(info[2]); if (phasedFile.length() < 1){ throw new PedFileException("Genotypes file is empty or non-existent: " + phasedFile.getName()); }else if (sampleFile.length() < 1){ throw new PedFileException("Sample file is empty or non-existent: " + sampleFile.getName()); }else if (legendFile.length() < 1){ throw new PedFileException("Legend file is empty or non-existent: " + legendFile.getName()); } //read in the individual ids data. try{ BufferedReader sampleBuffReader; if (Options.getGzip()){ FileInputStream sampleFis = new FileInputStream(sampleFile); GZIPInputStream sampleInputStream = new GZIPInputStream(sampleFis); sampleBuffReader = new BufferedReader(new InputStreamReader(sampleInputStream)); }else{ FileReader sampleReader = new FileReader(sampleFile); sampleBuffReader = new BufferedReader(sampleReader); } String sampleLine; while((sampleLine = sampleBuffReader.readLine())!=null){ StringTokenizer sampleTokenizer = new StringTokenizer(sampleLine); sampleData.add(sampleTokenizer.nextToken()); } }catch(NoSuchElementException nse){ throw new PedFileException("File format error: " + sampleFile.getName()); } //read in the legend data try{ BufferedReader legendBuffReader; if (Options.getGzip()){ FileInputStream legendFis = new FileInputStream(legendFile); GZIPInputStream legendInputStream = new GZIPInputStream(legendFis); legendBuffReader = new BufferedReader(new InputStreamReader(legendInputStream)); }else{ FileReader legendReader = new FileReader(legendFile); legendBuffReader = new BufferedReader(legendReader); } String legendLine; String zero, one; while((legendLine = legendBuffReader.readLine())!=null){ StringTokenizer legendSt = new StringTokenizer(legendLine); String markerid = legendSt.nextToken(); if (markerid.equalsIgnoreCase("rs") || markerid.equalsIgnoreCase("marker")){ //skip header continue; } legendMarkers.add(markerid); legendPositions.add(legendSt.nextToken()); byte[] legendBytes = new byte[2]; zero = legendSt.nextToken(); one = legendSt.nextToken(); if (zero.equalsIgnoreCase("A")){ legendBytes[0] = 1; }else if (zero.equalsIgnoreCase("C")){ legendBytes[0] = 2; }else if (zero.equalsIgnoreCase("G")){ legendBytes[0] = 3; }else if (zero.equalsIgnoreCase("T")){ legendBytes[0] = 4; }else{ throw new PedFileException("Invalid allele: " + zero); } if (one.equalsIgnoreCase("A")){ legendBytes[1] = 1; }else if (one.equalsIgnoreCase("C")){ legendBytes[1] = 2; }else if (one.equalsIgnoreCase("G")){ legendBytes[1] = 3; }else if (one.equalsIgnoreCase("T")){ legendBytes[1] = 4; }else{ throw new PedFileException("Invalid allele: " + one); } legendData.add(legendBytes); } 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); } }catch(NoSuchElementException nse){ throw new PedFileException("File format error: " + legendFile.getName()); } //read in the phased data. try{ BufferedReader phasedBuffReader; if (Options.getGzip()){ FileInputStream phasedFis = new FileInputStream(phasedFile); GZIPInputStream phasedInputStream = new GZIPInputStream(phasedFis); phasedBuffReader = new BufferedReader(new InputStreamReader(phasedInputStream)); }else{ FileReader phasedReader = new FileReader(phasedFile); phasedBuffReader = new BufferedReader(phasedReader); } String phasedLine; int columns = 0; String token; boolean even = false; int iterator = 0; while((phasedLine = phasedBuffReader.readLine()) != null){ StringTokenizer phasedSt = new StringTokenizer(phasedLine); columns = phasedSt.countTokens(); if(even){ iterator++; }else{ //Only set up a new individual every 2 lines. ind = new Individual(columns, true); try{ ind.setIndividualID((String)sampleData.get(iterator)); }catch (ArrayIndexOutOfBoundsException e){ throw new PedFileException("File error: Sample file is missing individual IDs"); } if (columns != legendData.size()){ throw new PedFileException("File error: invalid number of markers on Individual " + ind.getIndividualID()); } String details = (String)hapMapTranslate.get(ind.getIndividualID()); //exception in case of wierd compression combos in input files if (details == null){ throw new PedFileException("File format error: " + sampleFile.getName()); } 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()); } //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 (!even){ byteDataT = new byte[columns]; }else{ byteDataU = new byte[columns]; } while(phasedSt.hasMoreTokens()){ token = phasedSt.nextToken(); if (!even){ if (token.equalsIgnoreCase("0")){ byteDataT[index] = ((byte[])legendData.get(index))[0]; }else if (token.equalsIgnoreCase("1")){ byteDataT[index] = ((byte[])legendData.get(index))[1]; }else { throw new PedFileException("File format error: " + phasedFile.getName()); } }else{ if (token.equalsIgnoreCase("0")){ byteDataU[index] = ((byte[])legendData.get(index))[0]; }else if (token.equalsIgnoreCase("1")){ byteDataU[index] = ((byte[])legendData.get(index))[1]; }else if (Chromosome.getDataChrom().equalsIgnoreCase("chrx") && ind.getGender() == Individual.MALE && token.equalsIgnoreCase("-")){ //X male }else { throw new PedFileException("File format error: " + phasedFile.getName()); } } index++; } if (even){ if (ind.getGender() == Individual.MALE && Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ for(int i=0; i < columns; i++){ ind.addMarker(byteDataT[i], byteDataT[i]); } }else{ for(int i=0; i < columns; i++){ ind.addMarker(byteDataT[i], byteDataU[i]); } } } even = !even; } }catch(NoSuchElementException nse){ throw new PedFileException("File format error: " + phasedFile.getName()); } }
putValue(SHORT_DESCRIPTION, "Delete Selected"); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); setEnabled(false);
public DeleteSelectedAction() { super("Delete Selected", ASUtils.createJLFIcon("general/Delete", "Delete Selected", ArchitectFrame.getMainInstance().sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))); }
if (logger.isDebugEnabled()) { newMenu.addSeparator(); JMenuItem showListeners = new JMenuItem("Show Listeners"); showListeners.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SQLObject so = (SQLObject) getLastSelectedPathComponent(); if (so != null) { JOptionPane.showMessageDialog(DBTree.this, new JScrollPane(new JList(new java.util.Vector(so.getSQLObjectListeners())))); } } }); newMenu.add(showListeners); }
protected JPopupMenu setupPopupMenu() { JPopupMenu newMenu = new JPopupMenu(); newMenu.add(popupDBCSMenu = new JMenu("Add Connection")); newMenu.addSeparator(); // index 1 JMenuItem popupProperties = new JMenuItem(new DBCSPropertiesAction()); newMenu.add(popupProperties); // index 2 return newMenu; }
if (log.isDebugEnabled()) { log.debug( "Firing template body for match: " + match + " and node: " + node ); }
protected Action createAction() { return new Action() { public void run(Node node) throws Exception { xpathSource = node; getBody().run(context, output); } }; }
if (log.isDebugEnabled()) { log.debug( "Firing template body for match: " + match + " and node: " + node ); }
public void run(Node node) throws Exception { xpathSource = node; getBody().run(context, output); }
if ( log.isDebugEnabled() ) { log.debug( "adding template rule for match: " + match ); }
public void doTag(XMLOutput output) throws Exception { // for use by inner classes this.output = output; StylesheetTag tag = (StylesheetTag) findAncestorWithClass( StylesheetTag.class ); if (tag == null) { throw new JellyException( "This <template> tag must be used inside a <stylesheet> tag" ); } Rule rule = getRule(); if ( rule != null && tag != null) { rule.setMode( mode ); tag.addTemplate( rule ); } }
URL log4jPropertyURL = Photovault.class.getClassLoader().getResource( "log4j.properties");
URL log4jPropertyURL = Photovault.class.getClassLoader().getResource( "photovault_log4j.properties");
public static void main( String [] args ) { URL log4jPropertyURL = Photovault.class.getClassLoader().getResource( "log4j.properties"); PropertyConfigurator.configure( log4jPropertyURL ); Photovault app = new Photovault(); app.run(); }
public Destination getDestination() {
public Destination getDestination() throws JellyException, JMSException { if (destination == null) { if (subject != null) { destination = findDestination(subject); } }
public Destination getDestination() { return destination; }
sb.append(text.replace(' ', '_'));
sb.append(toIdentifier(text));
protected void appendIdentifier(StringBuffer sb, String text) { sb.append(text.replace(' ', '_')); }
parent.addChild(t);
public static SQLTable getDerivedInstance(SQLTable source, SQLDatabase parent) throws ArchitectException { SQLTable t = new SQLTable(parent); t.columnsPopulated = true; t.relationshipsPopulated = true; t.tableName = source.tableName; t.remarks = source.remarks; t.inherit(source); return t; }
String runString = "java -Xmx650m -classpath " + jarfile;
String runString = "java -Xmx10m -classpath " + jarfile;
public static void main(String[] args) { int exitValue = 0; String dir = System.getProperty("user.dir"); String sep = System.getProperty("file.separator"); String ver = System.getProperty("java.version"); System.out.println(ver); String jarfile = System.getProperty("java.class.path"); String argsToBePassed = new String(); boolean headless = false; for (int a = 0; a < args.length; a++){ argsToBePassed = argsToBePassed.concat(" " + args[a]); if (args[a].equals("-n") || args[a].equalsIgnoreCase("-nogui")){ headless=true; } } try { //if the nogui flag is present we force it into headless mode String runString = "java -Xmx650m -classpath " + jarfile; if (headless){ runString += " -Djava.awt.headless=true"; } runString += " edu.mit.wi.haploview.HaploView"+argsToBePassed; Process child = Runtime.getRuntime().exec(runString); //start up a thread to simply pump out all messages to stdout StreamGobbler isg = new StreamGobbler(child.getInputStream()); isg.start(); //while the child is alive we wait for error messages boolean dead = false; StringBuffer errorMsg = new StringBuffer("Fatal Error:\n"); BufferedReader besr = new BufferedReader(new InputStreamReader(child.getErrorStream())); String line = null; if ((line = besr.readLine()) != null) { errorMsg.append(line); //if the child generated an error message, kill it child.destroy(); dead = true; } //if the child died painfully throw up R.I.P. dialog if (dead){ if (headless){ System.out.println(errorMsg); }else{ JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, errorMsg, null, JOptionPane.ERROR_MESSAGE); } exitValue = -1; } } catch (Exception e) { if (headless){ System.out.println("Error:\nUnable to launch Haploview.\n"+e.getMessage()); }else{ JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, "Error:\nUnable to launch Haploview.\n"+e.getMessage(), null, JOptionPane.ERROR_MESSAGE); } } System.exit(exitValue); }
if ((line = besr.readLine()) != null) { errorMsg.append(line); child.destroy(); dead = true;
while ( !dead && (line = besr.readLine()) != null) { if(line.lastIndexOf("Memory") != -1) { errorMsg.append(line); child.destroy(); dead = true; }
public static void main(String[] args) { int exitValue = 0; String dir = System.getProperty("user.dir"); String sep = System.getProperty("file.separator"); String ver = System.getProperty("java.version"); System.out.println(ver); String jarfile = System.getProperty("java.class.path"); String argsToBePassed = new String(); boolean headless = false; for (int a = 0; a < args.length; a++){ argsToBePassed = argsToBePassed.concat(" " + args[a]); if (args[a].equals("-n") || args[a].equalsIgnoreCase("-nogui")){ headless=true; } } try { //if the nogui flag is present we force it into headless mode String runString = "java -Xmx650m -classpath " + jarfile; if (headless){ runString += " -Djava.awt.headless=true"; } runString += " edu.mit.wi.haploview.HaploView"+argsToBePassed; Process child = Runtime.getRuntime().exec(runString); //start up a thread to simply pump out all messages to stdout StreamGobbler isg = new StreamGobbler(child.getInputStream()); isg.start(); //while the child is alive we wait for error messages boolean dead = false; StringBuffer errorMsg = new StringBuffer("Fatal Error:\n"); BufferedReader besr = new BufferedReader(new InputStreamReader(child.getErrorStream())); String line = null; if ((line = besr.readLine()) != null) { errorMsg.append(line); //if the child generated an error message, kill it child.destroy(); dead = true; } //if the child died painfully throw up R.I.P. dialog if (dead){ if (headless){ System.out.println(errorMsg); }else{ JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, errorMsg, null, JOptionPane.ERROR_MESSAGE); } exitValue = -1; } } catch (Exception e) { if (headless){ System.out.println("Error:\nUnable to launch Haploview.\n"+e.getMessage()); }else{ JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, "Error:\nUnable to launch Haploview.\n"+e.getMessage(), null, JOptionPane.ERROR_MESSAGE); } } System.exit(exitValue); }
JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, errorMsg, null, JOptionPane.ERROR_MESSAGE);
Runnable showRip = new Runnable() { public void run() { JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, realErrorMsg, null, JOptionPane.ERROR_MESSAGE);} }; SwingUtilities.invokeAndWait(showRip);
public static void main(String[] args) { int exitValue = 0; String dir = System.getProperty("user.dir"); String sep = System.getProperty("file.separator"); String ver = System.getProperty("java.version"); System.out.println(ver); String jarfile = System.getProperty("java.class.path"); String argsToBePassed = new String(); boolean headless = false; for (int a = 0; a < args.length; a++){ argsToBePassed = argsToBePassed.concat(" " + args[a]); if (args[a].equals("-n") || args[a].equalsIgnoreCase("-nogui")){ headless=true; } } try { //if the nogui flag is present we force it into headless mode String runString = "java -Xmx650m -classpath " + jarfile; if (headless){ runString += " -Djava.awt.headless=true"; } runString += " edu.mit.wi.haploview.HaploView"+argsToBePassed; Process child = Runtime.getRuntime().exec(runString); //start up a thread to simply pump out all messages to stdout StreamGobbler isg = new StreamGobbler(child.getInputStream()); isg.start(); //while the child is alive we wait for error messages boolean dead = false; StringBuffer errorMsg = new StringBuffer("Fatal Error:\n"); BufferedReader besr = new BufferedReader(new InputStreamReader(child.getErrorStream())); String line = null; if ((line = besr.readLine()) != null) { errorMsg.append(line); //if the child generated an error message, kill it child.destroy(); dead = true; } //if the child died painfully throw up R.I.P. dialog if (dead){ if (headless){ System.out.println(errorMsg); }else{ JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, errorMsg, null, JOptionPane.ERROR_MESSAGE); } exitValue = -1; } } catch (Exception e) { if (headless){ System.out.println("Error:\nUnable to launch Haploview.\n"+e.getMessage()); }else{ JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, "Error:\nUnable to launch Haploview.\n"+e.getMessage(), null, JOptionPane.ERROR_MESSAGE); } } System.exit(exitValue); }
assertEquals("We did not generate move events",1,eventCounter.getMoved());
assertEquals("Even in Compound edits should still generate a move event for each setLocation",2,eventCounter.getMoved());
public void testMovement() { component.addPlayPenComponentListener( eventCounter); assertEquals("" + "We started out with the wrong number of events", 0,eventCounter.getEvents() ); //component.setMoving(true); //assertEquals("We did not generate a move start event",1,eventCounter.getStarts()); pp.startCompoundEdit("Starting move"); component.setLocation(1,1); component.setLocation(2,2); pp.endCompoundEdit("Ending move"); assertEquals("We did not generate move events",1,eventCounter.getMoved()); //component.setMoving(false); //assertEquals("We did not generate a move end event",1,eventCounter.getEnds()); component.setLocation(3,3); //assertEquals("We did not generate a move start event",2,eventCounter.getStarts()); assertEquals("We did not generate move events",2,eventCounter.getMoved()); //assertEquals("We did not generate a move end event",2,eventCounter.getEnds()); }
assertEquals("We did not generate move events",2,eventCounter.getMoved());
assertEquals("We did not generate move events",3,eventCounter.getMoved());
public void testMovement() { component.addPlayPenComponentListener( eventCounter); assertEquals("" + "We started out with the wrong number of events", 0,eventCounter.getEvents() ); //component.setMoving(true); //assertEquals("We did not generate a move start event",1,eventCounter.getStarts()); pp.startCompoundEdit("Starting move"); component.setLocation(1,1); component.setLocation(2,2); pp.endCompoundEdit("Ending move"); assertEquals("We did not generate move events",1,eventCounter.getMoved()); //component.setMoving(false); //assertEquals("We did not generate a move end event",1,eventCounter.getEnds()); component.setLocation(3,3); //assertEquals("We did not generate a move start event",2,eventCounter.getStarts()); assertEquals("We did not generate move events",2,eventCounter.getMoved()); //assertEquals("We did not generate a move end event",2,eventCounter.getEnds()); }
Widget parent = getParentWidget(); Widget widget = (Widget) createWidget(theClass, parent, style); if (parent != null) { attachWidgets(parent, widget); }
Widget parent = getParentWidget();
protected Object newInstance( Class theClass, Map attributes, XMLOutput output) throws JellyTagException { int style = getStyle(attributes); // now lets call the constructor with the parent Widget parent = getParentWidget(); Widget widget = (Widget) createWidget(theClass, parent, style); if (parent != null) { attachWidgets(parent, widget); } return widget; }
return widget; }
Widget widget = (Widget) createWidget(theClass, parent, style); if (parent != null) { attachWidgets(parent, widget); } return widget; }
protected Object newInstance( Class theClass, Map attributes, XMLOutput output) throws JellyTagException { int style = getStyle(attributes); // now lets call the constructor with the parent Widget parent = getParentWidget(); Widget widget = (Widget) createWidget(theClass, parent, style); if (parent != null) { attachWidgets(parent, widget); } return widget; }
int allele1=0, allele2=0, hom=0, het=0;
int allele1=0, allele2=0, hom=0, het=0, haploid = 0;
private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ if(currentInd.getGender() == 1) { if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0)){ //this is an x chrom for a male, so the only thing we need to check is if //allele1 matches either momallele1 or momallele2 if(allele1 != momAllele1 && allele1 != momAllele2) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else { //if gender is anything except 1 we assume female if(momAllele1 == momAllele2) { //mom hom and dad matches mom if(dadAllele1 == momAllele1) { //kid must be hom same allele if(allele1 != momAllele1 || allele2 != momAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else { //kid must be het if(allele1 == allele2 ){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ //mom het,so only need to check that at least one allele matches dad if(allele1 != dadAllele1 && allele2 != dadAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } } }else{ //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; }
if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){
if(Chromosome.getDataChrom().equals("chrx")){
private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ if(currentInd.getGender() == 1) { if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0)){ //this is an x chrom for a male, so the only thing we need to check is if //allele1 matches either momallele1 or momallele2 if(allele1 != momAllele1 && allele1 != momAllele2) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else { //if gender is anything except 1 we assume female if(momAllele1 == momAllele2) { //mom hom and dad matches mom if(dadAllele1 == momAllele1) { //kid must be hom same allele if(allele1 != momAllele1 || allele2 != momAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else { //kid must be het if(allele1 == allele2 ){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ //mom het,so only need to check that at least one allele matches dad if(allele1 != dadAllele1 && allele2 != dadAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } } }else{ //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; }
if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; }
private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ if(currentInd.getGender() == 1) { if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0)){ //this is an x chrom for a male, so the only thing we need to check is if //allele1 matches either momallele1 or momallele2 if(allele1 != momAllele1 && allele1 != momAllele2) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else { //if gender is anything except 1 we assume female if(momAllele1 == momAllele2) { //mom hom and dad matches mom if(dadAllele1 == momAllele1) { //kid must be hom same allele if(allele1 != momAllele1 || allele2 != momAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else { //kid must be het if(allele1 == allele2 ){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ //mom het,so only need to check that at least one allele matches dad if(allele1 != dadAllele1 && allele2 != dadAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } } }else{ //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; }
count[allele2]++;
if (!Chromosome.getDataChrom().equals("chrx") || currentInd.getGender() != 1) { if(allele1 != allele2) { founderHetCount++; }else{ founderHomCount[allele1]++; } count[allele2]++; }
private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ if(currentInd.getGender() == 1) { if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0)){ //this is an x chrom for a male, so the only thing we need to check is if //allele1 matches either momallele1 or momallele2 if(allele1 != momAllele1 && allele1 != momAllele2) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else { //if gender is anything except 1 we assume female if(momAllele1 == momAllele2) { //mom hom and dad matches mom if(dadAllele1 == momAllele1) { //kid must be hom same allele if(allele1 != momAllele1 || allele2 != momAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else { //kid must be het if(allele1 == allele2 ){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ //mom het,so only need to check that at least one allele matches dad if(allele1 != dadAllele1 && allele2 != dadAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } } }else{ //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; }
if(allele1 == allele2) { hom++; } else { het++;
if (!Chromosome.getDataChrom().equals("chrx") || currentInd.getGender() != 1) { if(allele1 == allele2) { hom++; }else { het++; } }else{ haploid++;
private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ if(currentInd.getGender() == 1) { if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0)){ //this is an x chrom for a male, so the only thing we need to check is if //allele1 matches either momallele1 or momallele2 if(allele1 != momAllele1 && allele1 != momAllele2) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else { //if gender is anything except 1 we assume female if(momAllele1 == momAllele2) { //mom hom and dad matches mom if(dadAllele1 == momAllele1) { //kid must be hom same allele if(allele1 != momAllele1 || allele2 != momAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else { //kid must be het if(allele1 == allele2 ){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ //mom het,so only need to check that at least one allele matches dad if(allele1 != dadAllele1 && allele2 != dadAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } } }else{ //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; }
double genopct = getGenoPercent(het, hom, missing);
double genopct = getGenoPercent(het, hom, haploid, missing);
private MarkerResult checkMarker(int loc)throws PedFileException{ MarkerResult result = new MarkerResult(); Individual currentInd; //int indivgeno=0, int missing=0, founderHetCount=0, mendErrNum=0; int allele1=0, allele2=0, hom=0, het=0; //Hashtable allgenos = new Hashtable(); Hashtable founderGenoCount = new Hashtable(); Hashtable kidgeno = new Hashtable(); //Hashtable parenthom = new Hashtable(); int[] founderHomCount = new int[5]; //Hashtable count = new Hashtable(); int[] count = new int[5]; for(int i=0;i<5;i++) { founderHomCount[i] =0; count[i]=0; } //loop through each family, check data for marker loc Enumeration famList = _pedFile.getFamList(); while(famList.hasMoreElements()){ Family currentFamily = _pedFile.getFamily((String)famList.nextElement()); Enumeration indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); //no allele data missing if(allele1 > 0 && allele2 >0){ //make sure entry has parents if (currentFamily.containsMember(currentInd.getMomID()) && currentFamily.containsMember(currentInd.getDadID())){ //do mendel check int momAllele1 = (currentFamily.getMember(currentInd.getMomID())).getMarkerA(loc); int momAllele2 = (currentFamily.getMember(currentInd.getMomID())).getMarkerB(loc); int dadAllele1 = (currentFamily.getMember(currentInd.getDadID())).getMarkerA(loc); int dadAllele2 = (currentFamily.getMember(currentInd.getDadID())).getMarkerB(loc); if(Chromosome.getDataChrom().equalsIgnoreCase("chrx")){ if(currentInd.getGender() == 1) { if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0)){ //this is an x chrom for a male, so the only thing we need to check is if //allele1 matches either momallele1 or momallele2 if(allele1 != momAllele1 && allele1 != momAllele2) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else { //if gender is anything except 1 we assume female if(momAllele1 == momAllele2) { //mom hom and dad matches mom if(dadAllele1 == momAllele1) { //kid must be hom same allele if(allele1 != momAllele1 || allele2 != momAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } }else { //kid must be het if(allele1 == allele2 ){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } }else{ //mom het,so only need to check that at least one allele matches dad if(allele1 != dadAllele1 && allele2 != dadAllele2){ mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } } }else{ //don't check if parents are missing any data if (!(momAllele1 == 0 || momAllele2 == 0 || dadAllele1 == 0 || dadAllele2 ==0)){ //mom hom if(momAllele1 == momAllele2){ //both parents hom if (dadAllele1 == dadAllele2){ //both parents hom same allele if (momAllele1 == dadAllele1){ //kid must be hom same allele if (allele1 != momAllele1 || allele2 != momAllele1) { mendErrNum ++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } //parents hom diff allele }else{ //kid must be het if (allele1 == allele2) { mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom hom dad het }else{ //kid can't be hom for non-momallele if (allele1 != momAllele1 && allele2 != momAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //mom het }else{ //dad hom if (dadAllele1 == dadAllele2){ //kid can't be hom for non-dadallele if(allele1 != dadAllele1 && allele2 != dadAllele1){ mendErrNum++; currentInd.zeroOutMarker(loc); currentFamily.getMember(currentInd.getMomID()).zeroOutMarker(loc); currentFamily.getMember(currentInd.getDadID()).zeroOutMarker(loc); } } //both parents het no mend err poss } } } } //end mendel check } } indList = currentFamily.getMemberList(); //loop through each individual in the current Family while(indList.hasMoreElements()){ currentInd = currentFamily.getMember((String)indList.nextElement()); if (currentInd.getZeroed(loc)){ allele1 = 0; allele2 = 0; }else{ allele1 = currentInd.getMarkerA(loc); allele2 = currentInd.getMarkerB(loc); } String familyID = currentInd.getFamilyID(); //no allele data missing if(allele1 > 0 && allele2 >0){ //indiv has no parents -- i.e. is a founder if(!currentFamily.hasAncestor(currentInd.getIndividualID())){ //set founderGenoCount if(founderGenoCount.containsKey(familyID)){ int value = ((Integer)founderGenoCount.get(familyID)).intValue() +1; founderGenoCount.put(familyID, new Integer(value)); } else{ founderGenoCount.put(familyID, new Integer(1)); } if(allele1 != allele2) { founderHetCount++; } else{ founderHomCount[allele1]++; } count[allele1]++; count[allele2]++; }else{ if(kidgeno.containsKey(familyID)){ int value = ((Integer)kidgeno.get(familyID)).intValue() +1; kidgeno.put(familyID, new Integer(value)); } else{ kidgeno.put(familyID, new Integer(1)); } } if(allele1 == allele2) { hom++; } else { het++; } } //missing data else missing++; } } double obsHET = getObsHET(het, hom); double freqStuff[] = null; try{ freqStuff = getFreqStuff(count); }catch (PedFileException pfe){ throw new PedFileException("More than two alleles at marker " + (loc+1)); } double preHET = freqStuff[0]; double maf = freqStuff[1]; //HW p value double pvalue = getPValue(founderHomCount, founderHetCount); //geno percent double genopct = getGenoPercent(het, hom, missing); // num of families with a fully genotyped trio //int famTrio =0; int famTrio = getNumOfFamTrio(_pedFile.getFamList(), founderGenoCount, kidgeno); //rating int rating = this.getRating(genopct, pvalue, mendErrNum,maf); result.setObsHet(obsHET); result.setPredHet(preHET); result.setMAF(maf); result.setHWpvalue(pvalue); result.setGenoPercent(genopct); result.setFamTrioNum(famTrio); result.setMendErrNum(mendErrNum); result.setRating(rating); return result; }
private double getGenoPercent(int het, int hom, int missing){ if (het+hom+missing == 0){
private double getGenoPercent(int het, int hom, int haploid, int missing){ if (het+hom+haploid+missing == 0){
private double getGenoPercent(int het, int hom, int missing){ if (het+hom+missing == 0){ return 0; }else{ return 100.0*(het+hom)/(het+hom+missing); } }
return 100.0*(het+hom)/(het+hom+missing);
return 100.0*(het+hom+haploid)/(het+hom+haploid+missing);
private double getGenoPercent(int het, int hom, int missing){ if (het+hom+missing == 0){ return 0; }else{ return 100.0*(het+hom)/(het+hom+missing); } }
log.info( "Parsing XPath expression: " + attributeValue );
if ( log.isDebugEnabled() ) { log.debug( "Parsing XPath expression: " + attributeValue ); }
public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws JellyException { // #### may need to include some namespace URI information in the XPath instance? if (attributeName.equals("select")) { log.info( "Parsing XPath expression: " + attributeValue ); try { XPath xpath = new Dom4jXPath(attributeValue); return new XPathExpression(xpath); } catch (JaxenException e) { throw new JellyException( "Could not parse XPath expression: \"" + attributeValue + "\" reason: " + e, e ); } } // will use the default expression instead return null; }
ProjectTag projectTag = (ProjectTag) findAncestorWithClass( ProjectTag.class ); Project project = projectTag.getProject();
Project project = getProject(); if (project == null) { throw new JellyException("No Project available"); }
public void doTag(final XMLOutput output) throws Exception { AttainTag attainTag = (AttainTag) findAncestorWithClass( AttainTag.class ); Session session = null; if ( attainTag == null ) { session = new JellySession( output ); } else { session = attainTag.getSession(); } ProjectTag projectTag = (ProjectTag) findAncestorWithClass( ProjectTag.class ); Project project = projectTag.getProject(); invokeBody(output); try { project.attainGoal( getName(), session ); } catch (UnattainableGoalException e) { Throwable root = e.getRootCause(); if ( root != null ) { if ( root instanceof JellyException ) { throw (JellyException) root; } if ( root instanceof UnattainableGoalException ) { throw e; } } else { e.fillInStackTrace(); throw e; } } }
((XMLWriter)contentHandler).flush();
if( contentHandler instanceof XMLWriter ) { ((XMLWriter)contentHandler).flush(); }
public void flush() throws IOException { ((XMLWriter)contentHandler).flush(); }
WeblogicApplicationForm appForm = (WeblogicApplicationForm)actionForm;
ApplicationForm appForm = (ApplicationForm)actionForm;
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { WeblogicApplicationForm appForm = (WeblogicApplicationForm)actionForm; //todo: Need something better String appId = String.valueOf(System.currentTimeMillis()); ApplicationConfig config = ApplicationConfigFactory.create(appId, appForm.getName(), appForm.getType(), appForm.getHost(), new Integer(appForm.getPort()), null, appForm.getUsername(), appForm.getPassword(), null); ApplicationConfigManager.addApplication(config); return mapping.findForward(Forwards.SUCCESS); }
new Integer(appForm.getPort()),
port,
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { WeblogicApplicationForm appForm = (WeblogicApplicationForm)actionForm; //todo: Need something better String appId = String.valueOf(System.currentTimeMillis()); ApplicationConfig config = ApplicationConfigFactory.create(appId, appForm.getName(), appForm.getType(), appForm.getHost(), new Integer(appForm.getPort()), null, appForm.getUsername(), appForm.getPassword(), null); ApplicationConfigManager.addApplication(config); return mapping.findForward(Forwards.SUCCESS); }
response.commit();
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { Tag handlerTag = (Tag) _tagMap.get(request.getMethod().toLowerCase()); if (null != handlerTag) { // setup the parameters in the jelly context JellyContext jellyContext = handlerTag.getContext(); jellyContext.setVariable( "pathInContext", pathInContext); jellyContext.setVariable( "pathParams", pathParams); jellyContext.setVariable( "request", request); jellyContext.setVariable( "response", response); try { handlerTag.invokeBody(_xmlOutput); // only call set handled if tag has not requested an override // if it has requested an override then reset the request if (null == jellyContext.getVariable(OVERRIDE_SET_HANDLED_VAR)) { request.setHandled(true); } else { jellyContext.removeVariable(OVERRIDE_SET_HANDLED_VAR); } } catch (Exception ex ) { throw new HttpException(HttpResponse.__500_Internal_Server_Error, "Error invoking method handler tag: " + ex.getLocalizedMessage()); } } else { log.info("No handler for request:" + request.getMethod() + " path:" + response.getHttpContext().getContextPath() + pathInContext); } return; }
super.setAttribute( name, value.toString() );
if ( value instanceof Expression ) { super.setAttribute( name, ((Expression) value).evaluateAsValue(context) ); } else { super.setAttribute( name, value.toString() ); }
public void setAttribute(String name, Object value) { if ( value == null ) { // should we send in null? super.setAttribute( name, "" ); } else { super.setAttribute( name, value.toString() ); } }
ApplicationHeartBeatThread associatedThread = null; for(ApplicationHeartBeatThread thread:threads){ if(thread.getApplicationConfig().equals(appConfig)){ associatedThread = thread; break; } } if(associatedThread == null){ logger.log(Level.WARNING, "Thread not found for application: {0}", appConfig); }else{ threads.remove(associatedThread); addApplication(appConfig); }
removeApplication(appConfig); addApplication(appConfig);
private void applicationChanged(ApplicationConfig appConfig) { ApplicationHeartBeatThread associatedThread = null; for(ApplicationHeartBeatThread thread:threads){ if(thread.getApplicationConfig().equals(appConfig)){ associatedThread = thread; break; } } if(associatedThread == null){ logger.log(Level.WARNING, "Thread not found for application: {0}", appConfig); }else{ threads.remove(associatedThread); addApplication(appConfig); } }
}else if(event instanceof ApplicationRemovedEvent){ removeApplication(((ApplicationRemovedEvent)event).getApplicationConfig());
public void start() { for (ApplicationConfig appConfig : ApplicationConfigManager .getAllApplications()) { // only add non-cluster applications if(!appConfig.isCluster()) addApplication(appConfig); } // TODO: perfect dependency to be injected via Spring framework --rk EventSystem eventSystem = EventSystem.getInstance(); /* Add the recorder to record the downtimes to the DB */ eventSystem.addListener(recorder, ApplicationEvent.class); /* application event listener to add */ eventSystem.addListener(new EventListener(){ public void handleEvent(EventObject event) { if(!(event instanceof ApplicationEvent)){ throw new IllegalArgumentException("event must be of type ApplicationEvent"); } if(event instanceof NewApplicationEvent){ addApplication(((NewApplicationEvent)event).getApplicationConfig()); }else if(event instanceof ApplicationChangedEvent){ applicationChanged(((ApplicationChangedEvent)event).getApplicationConfig()); } } }, ApplicationEvent.class); logger.info("ApplicationDowntimeService started."); }
}else if(event instanceof ApplicationRemovedEvent){ removeApplication(((ApplicationRemovedEvent)event).getApplicationConfig());
public void handleEvent(EventObject event) { if(!(event instanceof ApplicationEvent)){ throw new IllegalArgumentException("event must be of type ApplicationEvent"); } if(event instanceof NewApplicationEvent){ addApplication(((NewApplicationEvent)event).getApplicationConfig()); }else if(event instanceof ApplicationChangedEvent){ applicationChanged(((ApplicationChangedEvent)event).getApplicationConfig()); } }
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(); String libraryURI = "jelly:" + uri; if ( ! context.isTagLibraryRegistered(libraryURI) ) { context.registerTagLibrary(libraryURI, className); } } } catch (IOException e) { log.error("Could not load jelly properties from: " + url + ". Reason: " + e, e); } finally { try { in.close(); } catch (Exception e) { }
Properties properties = getJellyProperties(); 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(); String libraryURI = "jelly:" + uri; if ( ! context.isTagLibraryRegistered(libraryURI) ) { context.registerTagLibrary(libraryURI, className);
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(); String libraryURI = "jelly:" + uri; // don't overload any Mock Tags already if ( ! context.isTagLibraryRegistered(libraryURI) ) { context.registerTagLibrary(libraryURI, className); } } } catch (IOException e) { log.error("Could not load jelly properties from: " + url + ". Reason: " + e, e); } finally { try { in.close(); } catch (Exception e) { // ignore } } } }
value = false; if ( test != null ) {
ChooseTag tag = (ChooseTag) findAncestorWithClass( ChooseTag.class ); if ( tag == null ) { throw new JellyException( "This tag must be enclosed inside a <choose> tag" ); } if ( ! tag.isBlockEvaluated() && test != null ) {
public void doTag(XMLOutput output) throws Exception { value = false; if ( test != null ) { if ( test.evaluateAsBoolean( context ) ) { value = true; invokeBody(output); } } }
value = true;
tag.setBlockEvaluated(true);
public void doTag(XMLOutput output) throws Exception { value = false; if ( test != null ) { if ( test.evaluateAsBoolean( context ) ) { value = true; invokeBody(output); } } }
project.setProperty("ant.file", context.getCurrentURL().toExternalForm());
public static Project createProject(JellyContext context) { GrantProject project = new GrantProject(); project.setPropsHandler(new JellyPropsHandler(context)); 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(); project.getBaseDir(); return project; }
public void doTag(final XMLOutput output) throws Exception {
public void doTag(final XMLOutput output) throws JellyTagException {
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 { // create a new child context so that each test case // will have its own variable scopes JellyContext newContext = new JellyContext( context ); // disable inheritence of variables and tag libraries newContext.setExportLibraries(false); newContext.setExport(false); // invoke the test case 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); }
throw new JellyException( "Could not find a TestSuite to add this test to. This tag should be inside a <test:suite> tag" );
throw new JellyTagException( "Could not find a TestSuite to add this test to. This tag should be inside a <test:suite> tag" );
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 { // create a new child context so that each test case // will have its own variable scopes JellyContext newContext = new JellyContext( context ); // disable inheritence of variables and tag libraries newContext.setExportLibraries(false); newContext.setExport(false); // invoke the test case 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); }
registerTag("properties", PropertiesTag.class);
public UtilTagLibrary() { registerTag("tokenize", TokenizeTag.class); }
boolean definedHere = answer != null || variables.containsKey(name); if (definedHere) return answer;
public Object findVariable(String name) { Object answer = variables.get(name); if ( answer == null && parent != null ) { answer = parent.findVariable(name); } // ### this is a hack - remove this when we have support for pluggable Scopes if ( answer == null ) { try { answer = System.getProperty(name); } catch (SecurityException e) { // ignore security exceptions } } if (log.isDebugEnabled()) { log.debug("findVariable: " + name + " value: " + answer ); } return answer; }
if (definedHere) return value;
public Object getVariable(String name) { Object value = variables.get(name); if ( value == null && isInherit() ) { JellyContext parent = getParent(); if (parent != null) { value = parent.getVariable( name ); } } // ### this is a hack - remove this when we have support for pluggable Scopes if ( value == null ) { try { value = System.getProperty(name); } catch (SecurityException e) { // ignore security exceptions } } return value; }
instance.delete();
public void removeInstance( int instanceNum ) throws IndexOutOfBoundsException { ODMGXAWrapper txw = new ODMGXAWrapper(); ImageInstance instance = null; try { instance = (ImageInstance) getInstances().get(instanceNum ); } catch ( IndexOutOfBoundsException e ) { txw.abort(); throw e; } instances.remove( instance ); txw.commit(); }
this.selectionTimer = new Timer(500, new ActionListener() { public void actionPerformed(final ActionEvent e) { selectDocument(document.getId()); } });
private ListItem(final Document document) { super("DocumentListAvatar$ListItem", listItemBackground); this.document = document; this.selectionTimer = new Timer(500, new ActionListener() { public void actionPerformed(final ActionEvent e) { selectDocument(document.getId()); } }); setLayout(new GridBagLayout()); addMouseListener(this); final GridBagConstraints c = new GridBagConstraints(); final String iconPath = isClosed() ? "images/documentIconGray.png" : "images/documentIconBlue.png"; final JLabel documentIcon = LabelFactory.create(); documentIcon.setIcon(new ImageIcon(ResourceUtil.getURL(iconPath))); documentIcon.addMouseListener(new MouseAdapter() { public void mouseEntered(final MouseEvent e) { setCursor(new Cursor(Cursor.HAND_CURSOR)); } public void mouseExited(final MouseEvent e) { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); c.insets = new Insets(0, 16, 0, 0); add(documentIcon, c.clone()); // h: 20 px // x indent: 40 px c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; c.insets = new Insets(3, 16, 3, 0); final Font labelFont = hasBeenSeen() ? UIConstants.DefaultFont : UIConstants.DefaultFontBold; add(LabelFactory.create(labelFont, document.getName()), c.clone()); }
public void mouseEntered(final MouseEvent e) { startSelectionTimer(); }
public void mouseEntered(final MouseEvent e) { selectDocument(document.getId()); }
public void mouseEntered(final MouseEvent e) { startSelectionTimer(); }
stopSelectionTimer(); unselect();
unselectDocument(document.getId());
public void mouseExited(final MouseEvent e) { stopSelectionTimer(); unselect(); }
selectionTimer.stop();
private void select() { selectionTimer.stop(); setBackground(listItemBackgroundSelect); repaint(); }
this.selectionTimer = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent e) { controller.selectDocument(currentSelection); } }); this.selectionTimer.setRepeats(false);
DocumentListAvatar(final Controller controller) { super("DocumentListAvatar", new Color(255, 255, 255, 255)); this.controller = controller; this.documentItemMap = new Hashtable<UUID, Component>(20, 0.75F); setLayout(new GridBagLayout()); }
controller.selectDocument(documentId);
currentSelection = documentId; selectionTimer.start();
private void selectDocument(final UUID documentId) { Assert.assertNotNull("Cannot select null document.", documentId); // if it's the same do nothing if(this.currentSelection == documentId || documentId.equals(currentSelection)) { return; } final Collection<Component> listItems = documentItemMap.values(); for(Component c : listItems) { ((ListItem) c).unselect(); } final ListItem listItem = (ListItem) documentItemMap.get(documentId); listItem.select(); controller.selectDocument(documentId); }
dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return;
TablePane tp = c.importTableCopy((SQLTable) someData, dropLoc); dropLoc.x += tp.getPreferredSize().width + 5;
public void drop(DropTargetDropEvent dtde) { if (tpTarget != null) { tpTarget.getDropTarget().drop(dtde); return; } Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { DBTree dbtree = ArchitectFrame.getMainInstance().dbTree; // XXX: this is bad ArrayList paths = (ArrayList) t.getTransferData(importFlavor); Iterator pathIt = paths.iterator(); Point dropLoc = c.unzoomPoint(new Point(dtde.getLocation())); while (pathIt.hasNext()) { Object someData = dbtree.getNodeForDnDPath((int[]) pathIt.next()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dropLoc); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.importTableCopy(sourceTable, dropLoc); } } 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, dropLoc); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.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(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
dtde.acceptDrop(DnDConstants.ACTION_COPY);
public void drop(DropTargetDropEvent dtde) { if (tpTarget != null) { tpTarget.getDropTarget().drop(dtde); return; } Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { DBTree dbtree = ArchitectFrame.getMainInstance().dbTree; // XXX: this is bad ArrayList paths = (ArrayList) t.getTransferData(importFlavor); Iterator pathIt = paths.iterator(); Point dropLoc = c.unzoomPoint(new Point(dtde.getLocation())); while (pathIt.hasNext()) { Object someData = dbtree.getNodeForDnDPath((int[]) pathIt.next()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dropLoc); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.importTableCopy(sourceTable, dropLoc); } } 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, dropLoc); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.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(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
dtde.dropComplete(true); return;
public void drop(DropTargetDropEvent dtde) { if (tpTarget != null) { tpTarget.getDropTarget().drop(dtde); return; } Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { DBTree dbtree = ArchitectFrame.getMainInstance().dbTree; // XXX: this is bad ArrayList paths = (ArrayList) t.getTransferData(importFlavor); Iterator pathIt = paths.iterator(); Point dropLoc = c.unzoomPoint(new Point(dtde.getLocation())); while (pathIt.hasNext()) { Object someData = dbtree.getNodeForDnDPath((int[]) pathIt.next()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dropLoc); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.importTableCopy(sourceTable, dropLoc); } } 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, dropLoc); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.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(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
c.importTableCopy(sourceTable, dropLoc);
TablePane tp = c.importTableCopy(sourceTable, dropLoc); dropLoc.x += tp.getPreferredSize().width + 5;
public void drop(DropTargetDropEvent dtde) { if (tpTarget != null) { tpTarget.getDropTarget().drop(dtde); return; } Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { DBTree dbtree = ArchitectFrame.getMainInstance().dbTree; // XXX: this is bad ArrayList paths = (ArrayList) t.getTransferData(importFlavor); Iterator pathIt = paths.iterator(); Point dropLoc = c.unzoomPoint(new Point(dtde.getLocation())); while (pathIt.hasNext()) { Object someData = dbtree.getNodeForDnDPath((int[]) pathIt.next()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dropLoc); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.importTableCopy(sourceTable, dropLoc); } } 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, dropLoc); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.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(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
ufe.printStackTrace();
logger.error(ufe);
public void drop(DropTargetDropEvent dtde) { if (tpTarget != null) { tpTarget.getDropTarget().drop(dtde); return; } Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { DBTree dbtree = ArchitectFrame.getMainInstance().dbTree; // XXX: this is bad ArrayList paths = (ArrayList) t.getTransferData(importFlavor); Iterator pathIt = paths.iterator(); Point dropLoc = c.unzoomPoint(new Point(dtde.getLocation())); while (pathIt.hasNext()) { Object someData = dbtree.getNodeForDnDPath((int[]) pathIt.next()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dropLoc); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.importTableCopy(sourceTable, dropLoc); } } 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, dropLoc); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.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(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
ioe.printStackTrace();
logger.error(ioe);
public void drop(DropTargetDropEvent dtde) { if (tpTarget != null) { tpTarget.getDropTarget().drop(dtde); return; } Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { DBTree dbtree = ArchitectFrame.getMainInstance().dbTree; // XXX: this is bad ArrayList paths = (ArrayList) t.getTransferData(importFlavor); Iterator pathIt = paths.iterator(); Point dropLoc = c.unzoomPoint(new Point(dtde.getLocation())); while (pathIt.hasNext()) { Object someData = dbtree.getNodeForDnDPath((int[]) pathIt.next()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dropLoc); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.importTableCopy(sourceTable, dropLoc); } } 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, dropLoc); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.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(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
ex.printStackTrace();
logger.error(ex);
public void drop(DropTargetDropEvent dtde) { if (tpTarget != null) { tpTarget.getDropTarget().drop(dtde); return; } Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { DBTree dbtree = ArchitectFrame.getMainInstance().dbTree; // XXX: this is bad ArrayList paths = (ArrayList) t.getTransferData(importFlavor); Iterator pathIt = paths.iterator(); Point dropLoc = c.unzoomPoint(new Point(dtde.getLocation())); while (pathIt.hasNext()) { Object someData = dbtree.getNodeForDnDPath((int[]) pathIt.next()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.importTableCopy((SQLTable) someData, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dropLoc); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dropLoc); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.importTableCopy(sourceTable, dropLoc); } } 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, dropLoc); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.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(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(CompareDMPanel.this), "Unexpected architect exception in ConnectionListener" + "\n" + e, "Error", JOptionPane.ERROR_MESSAGE);
public void doStuff() throws Exception { try { ListerProgressBarUpdater progressBarUpdater = new ListerProgressBarUpdater(progressBar, this); new javax.swing.Timer(100, progressBarUpdater).start(); db.populate(); } catch (ArchitectException e) { logger.debug( "Unexpected architect exception in ConnectionListener", e); } }
String newValue = project.replaceProperties( (String) value );
String newValue = ProjectHelper.replaceProperties( project, (String) value, project.getProperties() );
public void setAttribute(String name, Object value) { // Catch the normal setAttribute, and call throw Ant's // normal property-deref routines. Project project = task.getProject(); String newValue = project.replaceProperties( (String) value ); super.setAttribute( name, newValue ); }