rem
stringlengths
0
477k
add
stringlengths
0
313k
context
stringlengths
6
599k
setFkConnectionPoint(ui.closestEdgePoint(false, getFkConnectionPoint()));
setFkConnectionPoint(((RelationshipUI) getUI()).closestEdgePoint(false, getFkConnectionPoint()));
public void componentResized(PlayPenComponentEvent e) { logger.debug("Component "+e.getPPComponent().getName()+" changed size"); if (e.getPPComponent() == pkTable) { setPkConnectionPoint(ui.closestEdgePoint(true, getPkConnectionPoint())); // true == PK } if (e.getPPComponent() == fkTable) { setFkConnectionPoint(ui.closestEdgePoint(false, getFkConnectionPoint())); // false == FK } }
p = r.ui.closestEdgePoint(movingPk, p);
p = ((RelationshipUI) r.getUI()).closestEdgePoint(movingPk, p);
protected Point translatePoint(Point p) { if (movingPk) { p.x = p.x - r.getPkTable().getX(); p.y = p.y - r.getPkTable().getY(); p = r.ui.closestEdgePoint(movingPk, p); } else { p.x = p.x - r.getFkTable().getX(); p.y = p.y - r.getFkTable().getY(); p = r.ui.closestEdgePoint(movingPk, p); } return p; }
return ui.getFkConnectionPoint();
return ((RelationshipUI) getUI()).getFkConnectionPoint();
public Point getFkConnectionPoint() { return ui.getFkConnectionPoint(); }
return ui.getPkConnectionPoint();
return ((RelationshipUI) getUI()).getPkConnectionPoint();
public Point getPkConnectionPoint() { return ui.getPkConnectionPoint(); }
return ui.getPreferredLocation();
return ((RelationshipUI) getUI()).getPreferredLocation();
public Point getPreferredLocation() { return ui.getPreferredLocation(); }
return ui.intersects(region);
return ((RelationshipUI) getUI()).intersects(region);
public boolean intersects(Rectangle region) { return ui.intersects(region); }
ui.setFkConnectionPoint(p);
((RelationshipUI) getUI()).setFkConnectionPoint(p);
public void setFkConnectionPoint(Point p) { ui.setFkConnectionPoint(p); revalidate(); }
ui.setPkConnectionPoint(p);
((RelationshipUI) getUI()).setPkConnectionPoint(p);
public void setPkConnectionPoint(Point p) { ui.setPkConnectionPoint(p); revalidate(); }
public TDTResult() {
public TDTResult(SNP tempSNP) {
public TDTResult() { counts = new int[2][2]; }
this.theSNP = tempSNP;
public TDTResult() { counts = new int[2][2]; }
public double getChiSq() {
public double getChiSq(int type) {
public double getChiSq() { if(!this.chiSet){ this.chiSqVal = Math.pow( (this.counts[0][0] - this.counts[0][1]),2) / (this.counts[0][0] + this.counts[0][1]); this.chiSqVal = Math.rint(this.chiSqVal*1000.0)/1000.0; this.chiSet = true; } return this.chiSqVal; }
this.chiSqVal = Math.pow( (this.counts[0][0] - this.counts[0][1]),2) / (this.counts[0][0] + this.counts[0][1]);
if (type == 1){ this.chiSqVal = Math.pow( (this.counts[0][0] - this.counts[0][1]),2) / (this.counts[0][0] + this.counts[0][1]); }else{ int N = counts[0][0] + counts[0][1] + counts[1][0] + counts[1][1]; for (int i = 0; i < 2; i++){ for (int j = 0; j < 2; j++){ double nij = ((double)(counts[i][0] + counts[i][1])*(counts[0][j] + counts[1][j]))/N; this.chiSqVal += Math.pow( (this.counts[i][j] - nij), 2) / nij; } } }
public double getChiSq() { if(!this.chiSet){ this.chiSqVal = Math.pow( (this.counts[0][0] - this.counts[0][1]),2) / (this.counts[0][0] + this.counts[0][1]); this.chiSqVal = Math.rint(this.chiSqVal*1000.0)/1000.0; this.chiSet = true; } return this.chiSqVal; }
public double getPValue() {
public String getPValue() {
public double getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*getChiSq()); return Math.rint(pval*10000.0)/10000.0; }
pval= MathUtil.gammq(.5,.5*getChiSq()); return Math.rint(pval*10000.0)/10000.0;
pval= MathUtil.gammq(.5,.5*this.chiSqVal); DecimalFormat df; if (pval < 0.0001){ df = new DecimalFormat("0.0000E0"); }else{ df = new DecimalFormat(); df.setMaximumFractionDigits(4); } String formattedNumber = df.format(pval, new StringBuffer(), new FieldPosition(NumberFormat.INTEGER_FIELD)).toString(); return formattedNumber;
public double getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*getChiSq()); return Math.rint(pval*10000.0)/10000.0; }
public String getTURatio() { return this.counts[0][0] + ":" + this.counts[0][1];
public String getTURatio(int type) { if (type == 1){ return this.counts[0][0] + ":" + this.counts[0][1]; }else{ return this.counts[0][0] + ":" + this.counts[0][1] + ", " + this.counts[1][0] + ":" + this.counts[1][1]; }
public String getTURatio() { return this.counts[0][0] + ":" + this.counts[0][1]; }
InputStream in = new FileInputStream(name); Script script = parser.parse(in); script = script.compile(); log.info("Evaluating: " + script); script.run(parser.getContext(), output);
context.runScript(new File(name), output);
protected void runScript(String name) throws Exception { InputStream in = new FileInputStream(name); Script script = parser.parse(in); script = script.compile(); log.info("Evaluating: " + script); script.run(parser.getContext(), output); }
runScript("src/test/org/apache/commons/jelly/define/babelfishTaglib.jelly");
public void testParse() throws Exception { StringWriter buffer = new StringWriter(); output = XMLOutput.createXMLOutput(buffer); runScript("src/test/org/apache/commons/jelly/define/babelfishTaglib.jelly"); runScript("src/test/org/apache/commons/jelly/define/example.jelly"); log.info("The output was as follows"); log.info(buffer.toString()); }
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) {
private static void displayExceptionDialog(final Component parent, String message, final Throwable throwable) { JDialog dialog;
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { }
Throwable t = throwable; StringWriter stringWriter = new StringWriter(); final PrintWriter traceWriter = new PrintWriter(stringWriter); do { printStackTrace(t, traceWriter); t = t.getCause(); if (t != null) { traceWriter.println("Caused by:"); } } while (t != null); traceWriter.close();
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString()));
final JScrollPane detailScroller = new JScrollPane(new JTextArea(stringWriter.toString()));
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
dialog.add(messageComponent, BorderLayout.CENTER);
finalDialogReference.add(messageComponent, BorderLayout.CENTER);
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
dialog.pack();
finalDialogReference.pack();
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
dialog.remove(messageComponent);
finalDialogReference.remove(messageComponent);
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
dialog.setSize(SIZE_NODETAILS);
finalDialogReference.setSize(SIZE_NODETAILS);
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
dialog.dispose(); dialog.setVisible(false);
finalDialogReference.dispose(); finalDialogReference.setVisible(false);
private static void displayExceptionDialog(Component parent, String message, Throwable throwable) { if (parent == null) { logger.error("displayExceptionDialog with null parent for message " + message); } else if (parent instanceof Frame) { dialog = new JDialog((Frame) parent, "Error Report"); } else if (parent instanceof Dialog) { dialog = new JDialog((Dialog)parent, "Error Report"); } else { logger.error("non-null parent component is neither frame nor dialog"); } logger.debug("displayExceptionDialog: showing exception dialog for:", throwable); dialog.setLocationRelativeTo(parent); ((JComponent)dialog.getContentPane()).setBorder( BorderFactory.createEmptyBorder(10, 10, 5, 5)); // Details information final StringWriter traceWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(traceWriter)); try { traceWriter.close(); } catch (IOException e1) { // who cares!? } JPanel top = new JPanel(new GridLayout(0, 1, 5, 5)); final String LAYOUT_START = "<html><font color='red' size='+1'>"; final String LAYOUT_END = "</font>"; if (message == null) { message = "Unexpected error"; } JLabel messageLabel = new JLabel(LAYOUT_START + message + LAYOUT_END); messageLabel.setIcon(StatusIcon.getFailIcon()); top.add(messageLabel); JLabel errClassLabel = new JLabel("Exception type: " + throwable.getClass().getName()); top.add(errClassLabel); String excDetailMessage = throwable.getMessage(); if (excDetailMessage != null) { top.add(new JLabel("Detail string: " + excDetailMessage)); } dialog.add(top, BorderLayout.NORTH); final JScrollPane detailScroller = new JScrollPane(new JTextArea(traceWriter.toString())); final JPanel messageComponent = new JPanel(new BorderLayout()); messageComponent.add(detailScroller, BorderLayout.CENTER); messageComponent.setPreferredSize(new Dimension(700, 400)); final Dimension SIZE_NODETAILS = new Dimension(350, 200); // XXX This button should be at the right side of the // error text instead of the bottom, so it wouldn't jump // around when you activate it. final JButton detailsButton = new JButton("Show Details"); // N.B. AbstractAction in a JButton does not update the label // automatically when you change the SHORT_DESCRIPTION value. ActionListener detailsAction = new ActionListener() { boolean showDetails = true; public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; } }; detailsButton.addActionListener(detailsAction); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); } }); JPanel bottom = new JPanel(); bottom.add(detailsButton); bottom.add(okButton); dialog.add(bottom, BorderLayout.SOUTH); dialog.setSize(SIZE_NODETAILS); if (parent == null) { UtilGUI.centre(dialog); } dialog.setVisible(true); }
dialog.add(messageComponent, BorderLayout.CENTER);
finalDialogReference.add(messageComponent, BorderLayout.CENTER);
public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; }
dialog.pack();
finalDialogReference.pack();
public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; }
dialog.remove(messageComponent);
finalDialogReference.remove(messageComponent);
public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; }
dialog.setSize(SIZE_NODETAILS);
finalDialogReference.setSize(SIZE_NODETAILS);
public void actionPerformed(ActionEvent e) { // System.out.println("showDetails=" + showDetails); if (showDetails) { dialog.add(messageComponent, BorderLayout.CENTER); detailsButton.setText("Hide Details"); dialog.pack(); } else /* hide details */ { dialog.remove(messageComponent); detailsButton.setText("Show Details"); dialog.setSize(SIZE_NODETAILS); } showDetails = ! showDetails; }
dialog.dispose(); dialog.setVisible(false);
finalDialogReference.dispose(); finalDialogReference.setVisible(false);
public void actionPerformed(ActionEvent e) { dialog.dispose(); dialog.setVisible(false); }
label.paint(imageGraphics);
label.repaint();
public void dragGestureRecognized(DragGestureEvent dge) { PlayPenComponent c = contentPane.getComponentAt( unzoomPoint(((MouseEvent) dge.getTriggerEvent()).getPoint())); if ( c instanceof TablePane ) { TablePane tp = (TablePane) c; int colIndex = TablePane.COLUMN_INDEX_NONE; Point dragOrigin = tp.getPlayPen().unzoomPoint(new Point(dge.getDragOrigin())); dragOrigin.x -= tp.getX(); dragOrigin.y -= tp.getY(); // ignore drag events that aren't from the left mouse button if (dge.getTriggerEvent() instanceof MouseEvent && (dge.getTriggerEvent().getModifiers() & InputEvent.BUTTON1_MASK) == 0) return; // ignore drag events if we're in the middle of a createRelationship if (ArchitectFrame.getMainInstance().createRelationshipIsActive()) { logger.debug("CreateRelationship() is active, short circuiting DnD."); return; } try { colIndex = tp.pointToColumnIndex(dragOrigin); } catch (ArchitectException e) { logger.error("Got exception while translating drag point", e); } logger.debug("Recognized drag gesture on "+tp.getName()+"! origin="+dragOrigin +"; col="+colIndex); try { logger.debug("DGL: colIndex="+colIndex+",columnsSize="+tp.getModel().getColumns().size()); if (colIndex == TablePane.COLUMN_INDEX_TITLE) { // we don't use this because it often misses drags // that start near the edge of the titlebar logger.debug("Discarding drag on titlebar (handled by mousePressed())"); draggingTablePanes = true; } else if (colIndex >= 0 && colIndex < tp.getModel().getColumns().size()) { // export column as DnD event if (logger.isDebugEnabled()) { logger.debug("Exporting column "+colIndex+" with DnD"); } tp.draggingColumn = tp.getModel().getColumn(colIndex); DBTree tree = ArchitectFrame.getMainInstance().dbTree; int[] path = tree.getDnDPathToNode(tp.draggingColumn); if (logger.isDebugEnabled()) { StringBuffer array = new StringBuffer(); for (int i = 0; i < path.length; i++) { array.append(path[i]); array.append(","); } logger.debug("Path to dragged node: "+array); } // export list of DnD-type tree paths ArrayList paths = new ArrayList(1); paths.add(path); logger.info("DBTree: exporting 1-item list of DnD-type tree path"); JLabel label = new JLabel(tp.getModel().getName()+"."+tp.draggingColumn.getName()); Dimension labelSize = label.getPreferredSize(); label.setSize(labelSize); // because a LayoutManager would normally do this BufferedImage dragImage = new BufferedImage(labelSize.width, labelSize.height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D imageGraphics = dragImage.createGraphics(); // XXX: it would be nice to make this transparent, but initial attempts using AlphaComposite failed (on OS X) label.paint(imageGraphics); imageGraphics.dispose(); dge.getDragSource().startDrag(dge, null, dragImage, new Point(0, 0), new DnDTreePathTransferable(paths), tp); } } catch (ArchitectException ex) { logger.error("Couldn't drag column", ex); JOptionPane.showMessageDialog(tp.getPlayPen(), "Can't drag column: "+ex.getMessage()); } } else { return; } }
photo.createThumbnail();
public void testThumbnailCreateCorruptInstances() throws Exception { String testImgDir = "c:\\java\\photovault\\testfiles"; String fname = "test1.jpg"; File f = new File( testImgDir, fname ); PhotoInfo photo = null; try { photo = PhotoInfo.addToDB( f ); } catch ( PhotoNotFoundException e ) { fail( "Could not find photo: " + e.getMessage() ); } // Create the thumbnail so that the database shows that such beast exist photo.createThumbnail(); // Corrupt the database by deleting the actual image files // that instances refer to int numInstances = photo.getNumInstances(); for ( int n = 0; n < numInstances ; n++ ) { ImageInstance instance = photo.getInstance( n ); File instFile = instance.getImageFile(); instFile.delete(); } try { Thumbnail thumb = photo.getThumbnail(); assertNotNull( thumb ); assertTrue( "Database is corrupt, should return default thumbnail", thumb == Thumbnail.getDefaultThumbnail() ); assertEquals( "Database is corrupt, getThumbnail should not create a new instance", numInstances, photo.getNumInstances() ); } finally { // Clean up in any case photo.delete(); } }
photo.createThumbnail();
public void testThumbnailCreateCorruptInstances() throws Exception { String testImgDir = "c:\\java\\photovault\\testfiles"; String fname = "test1.jpg"; File f = new File( testImgDir, fname ); PhotoInfo photo = null; try { photo = PhotoInfo.addToDB( f ); } catch ( PhotoNotFoundException e ) { fail( "Could not find photo: " + e.getMessage() ); } // Create the thumbnail so that the database shows that such beast exist photo.createThumbnail(); // Corrupt the database by deleting the actual image files // that instances refer to int numInstances = photo.getNumInstances(); for ( int n = 0; n < numInstances ; n++ ) { ImageInstance instance = photo.getInstance( n ); File instFile = instance.getImageFile(); instFile.delete(); } try { Thumbnail thumb = photo.getThumbnail(); assertNotNull( thumb ); assertTrue( "Database is corrupt, should return default thumbnail", thumb == Thumbnail.getDefaultThumbnail() ); assertEquals( "Database is corrupt, getThumbnail should not create a new instance", numInstances, photo.getNumInstances() ); } finally { // Clean up in any case photo.delete(); } }
new File(CoreUtils.getLogDir()).mkdirs();
public static void main(String[] args) throws Exception{ UserManager userManager = UserManager.getInstance(); User user = null; char[] password = null; int invalidAttempts = 0; if(args.length == 1){ password = args[0].toCharArray(); user = userManager.verifyUsernamePassword( AuthConstants.USER_ADMIN, password); /* invalid password was tried */ if(user == null){ invalidAttempts ++; } } while(user == null){ if(invalidAttempts > 0){ System.out.println("Invalid Admin Password."); } /* get the password */ password = PasswordField.getPassword("Enter password:"); /* the password should match for the admin user */ user = userManager.verifyUsernamePassword( AuthConstants.USER_ADMIN, password); invalidAttempts ++; if(invalidAttempts >= 3){ break; } } /* exit if the admin password is still invalid */ if(user == null){ System.out.println("Number of invalid attempts exceeded. Exiting !"); return; } /* set admin password as the stop key */ final JettyStopKey stopKey = new JettyStopKey(new String(password)); System.setProperty("STOP.KEY", stopKey.toString()); /* set stop.port */ System.setProperty("STOP.PORT", JManageProperties.getStopPort()); /* create logs dir */ new File(CoreUtils.getLogDir()).mkdirs(); /* initialize ServiceFactory */ ServiceFactory.init(ServiceFactory.MODE_LOCAL); /* initialize crypto */ Crypto.init(password); /* clear the password */ Arrays.fill(password, ' '); /* load ACLs */ ACLStore.getInstance(); /* load application types */ ApplicationTypes.init(); /* start the AlertEngine */ AlertEngine.getInstance().start(); /* start the application */ start(); }
theData.filteredDPrimeTable = theData.getFilteredTable();
public void stateChanged(ChangeEvent e) { viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ 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,7)).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.guessBlocks(currentBlockDef); theData.filteredDPrimeTable = theData.getFilteredTable(); //hack-y way to refresh the image dPrimeDisplay.setVisible(false); dPrimeDisplay.setVisible(true); hapDisplay.theData = theData; try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } }
tdtPanel.refreshTable();
public void stateChanged(ChangeEvent e) { viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ 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,7)).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.guessBlocks(currentBlockDef); theData.filteredDPrimeTable = theData.getFilteredTable(); //hack-y way to refresh the image dPrimeDisplay.setVisible(false); dPrimeDisplay.setVisible(true); hapDisplay.theData = theData; try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } }
e.getSQLSource().removeSQLObjectListener(this); try { ArchitectUtils.unlistenToHierarchy(this,((SQLTable)e.getSQLSource().getParent()).getColumnsFolder()); } catch (ArchitectException e1) { throw new ArchitectRuntimeException(e1); }
public void dbChildrenRemoved(SQLObjectEvent e) { logger.debug("dbChildrenRemoved event! parent="+e.getSource()+"; children="+e.getChildren()); SQLTable.Folder f = (SQLTable.Folder) e.getSource(); if (f.getType() == SQLTable.Folder.EXPORTED_KEYS) { SQLObject[] removedRels = e.getChildren(); int size = removedRels.length; for (int i = 0; i < size; i++) { SQLRelationship r = (SQLRelationship) removedRels[i]; if (r == SQLRelationship.this) { r.getFkTable().removeImportedKey(r); logger.debug("Removing references for mappings: "+getMappings()); for (ColumnMapping cm : r.getMappings()) { logger.debug("Removing mapping "+ cm); cm.getFkColumn().removeReference(); } } } } else if (f.getType() == SQLTable.Folder.COLUMNS) { SQLObject[] cols = e.getChildren(); for (int i = 0; i < cols.length; i++) { SQLColumn col = (SQLColumn) cols[i]; col.removeSQLObjectListener(this); try { ensureNotInMapping(col); } catch (ArchitectException ex) { logger.warn("Couldn't remove mapped FK columns", ex); } } } }
return expression.getExpression();
return "${" + expression.getExpression() + "}";
public String getExpressionText() { return expression.getExpression(); }
ih.storeElement( project, parentObject, nested, tagName );
ih.storeElement( project, parentObject, nested, tagName.toLowerCase() );
public void doTag(XMLOutput output) throws JellyTagException { Project project = getAntProject(); String tagName = getTagName(); Object parentObject = findBeanAncestor(); Object parentTask = findParentTaskObject(); // lets assume that Task instances are not nested inside other Task instances // for example <manifest> inside a <jar> should be a nested object, where as // if the parent is not a Task the <manifest> should create a ManifestTask // // also its possible to have a root Ant tag which isn't a task, such as when // defining <fileset id="...">...</fileset> Object nested = null; if (parentObject != null && !( parentTask instanceof TaskContainer) ) { nested = createNestedObject( parentObject, tagName ); } if (nested == null) { task = createTask( tagName ); if (task != null) { if ( log.isDebugEnabled() ) { log.debug( "Creating an ant Task for name: " + tagName ); } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { Object[] args = { body }; try { method.invoke(this.task, args); } catch (IllegalAccessException e) { throw new JellyTagException(e); } catch (InvocationTargetException e) { throw new JellyTagException(e); } } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } } if (task == null) { if (nested == null) { if ( log.isDebugEnabled() ) { log.debug( "Trying to create a data type for tag: " + tagName ); } nested = createDataType( tagName ); } else { if ( log.isDebugEnabled() ) { log.debug( "Created nested property tag: " + tagName ); } } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { if (log.isDebugEnabled()) { log.debug("About to set the: " + tagName + " property on: " + parentObject + " to value: " + nested + " with type: " + nested.getClass() ); } ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { log.warn( "Caught exception setting nested: " + tagName, e ); } // now try to set the property for good measure // as the storeElement() method does not // seem to call any setter methods of non-String types try { BeanUtils.setProperty( parentObject, tagName, nested ); } catch (Exception e) { log.debug("Caught exception trying to set property: " + tagName + " on: " + parentObject); } } } else { log.warn("Could not convert tag: " + tagName + " into an Ant task, data type or property"); // lets treat this tag as static XML... StaticTag tag = new StaticTag("", tagName, tagName); tag.setParent( getParent() ); tag.setBody( getBody() ); tag.setContext(context); for (Iterator iter = getAttributes().entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); tag.setAttribute(name, value); } tag.doTag(output); } } }
private void putResult(ProfileResult profileResult) {
public void putResult(ProfileResult profileResult) {
private void putResult(ProfileResult profileResult) { if (logger.isDebugEnabled()) { logger.debug("[instance "+hashCode()+"]" + " Adding new profile result for "+profileResult.getProfiledObject().getName()+ " existing profile count: "+results.size()); } results.put(profileResult.getProfiledObject(), profileResult); }
final ObjectName objectName = context.getObjectName(); final ApplicationConfig appConfig = context.getApplicationConfig(); List applications = null; if(appConfig.isCluster()){ applications = appConfig.getApplications(); }else{ applications = new ArrayList(1); applications.add(appConfig); } for(Iterator it=applications.iterator(); it.hasNext(); ){ final ApplicationConfig childAppConfig = (ApplicationConfig)it.next(); try { final ServerConnection serverConnection = ServerConnector.getServerConnection(childAppConfig); List attributeList = buildAttributeList(request, childAppConfig.getApplicationId()); serverConnection.setAttributes(objectName, attributeList); String logString = getLogString(attributeList); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Updated the attributes of application:" + childAppConfig.getName() + ", object name:" + objectName.getCanonicalName() + logString); } catch (ConnectionFailedException e) { logger.log(Level.FINE, "Error connecting to :" + childAppConfig.getName(), e); } }
final String objectName = context.getObjectName().getCanonicalName(); final String appName = context.getApplicationConfig().getName(); MBeanService mbeanService = ServiceFactory.getMBeanService(); mbeanService.updateAttributes(Utils.getServiceContext(context), request, objectName, appName);
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { final ObjectName objectName = context.getObjectName(); final ApplicationConfig appConfig = context.getApplicationConfig(); List applications = null; if(appConfig.isCluster()){ applications = appConfig.getApplications(); }else{ applications = new ArrayList(1); applications.add(appConfig); } for(Iterator it=applications.iterator(); it.hasNext(); ){ final ApplicationConfig childAppConfig = (ApplicationConfig)it.next(); try { final ServerConnection serverConnection = ServerConnector.getServerConnection(childAppConfig); List attributeList = buildAttributeList(request, childAppConfig.getApplicationId()); serverConnection.setAttributes(objectName, attributeList); String logString = getLogString(attributeList); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Updated the attributes of application:" + childAppConfig.getName() + ", object name:" + objectName.getCanonicalName() + logString); } catch (ConnectionFailedException e) { logger.log(Level.FINE, "Error connecting to :" + childAppConfig.getName(), e); } } return mapping.findForward(Forwards.SUCCESS); }
Collections.sort((List)value, xpCmp);
Collections.sort(list, xpCmp); } if(list.isEmpty()) { value = null;
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException { if (var == null) { throw new MissingAttributeException( "var" ); } if (select == null) { throw new MissingAttributeException( "select" ); } Object xpathContext = getXPathContext(); Object value = null; try { if(single!=null && single.booleanValue()==true) { value = select.selectSingleNode(xpathContext); } else { value = select.evaluate(xpathContext); } } catch (JaxenException e) { throw new JellyTagException(e); } if (value instanceof List) { // sort the list if xpCmp is set. if (xpCmp != null && (xpCmp.getXpath() != null)) { Collections.sort((List)value, xpCmp); } } switch ( determineReturnType() ) { case RETURN_NODE_LIST: value = valueAsList(value); break; case RETURN_FIRST_NODE: value = valueAsSingle(value); break; case RETURN_STRING_LIST: value = nodeListToStringList(valueAsList(value)); break; case RETURN_DELIMITED_STRING_LIST: value = joinDelimitedElements(nodeListToStringList(valueAsList(value))); break; case RETURN_FIRST_AS_STRING: value = singleValueAsString(valueAsSingle(value)); break; } //log.info( "Evaluated xpath: " + select + " as: " + value + " of type: " + value.getClass().getName() ); context.setVariable(var, value); }
switch ( determineReturnType() ) { case RETURN_NODE_LIST: value = valueAsList(value); break; case RETURN_FIRST_NODE: value = valueAsSingle(value); break; case RETURN_STRING_LIST: value = nodeListToStringList(valueAsList(value)); break; case RETURN_DELIMITED_STRING_LIST: value = joinDelimitedElements(nodeListToStringList(valueAsList(value))); break; case RETURN_FIRST_AS_STRING: value = singleValueAsString(valueAsSingle(value)); break;
if (single!=null) { if (single.booleanValue() == true) { if(value instanceof List) { List l = (List) value; if (l.size() == 0) value=null; else value=l.get(0); } } else { if(! (value instanceof List) ) { List l = null; if (value==null) { l = new ArrayList(0); } else { l = new ArrayList(1); l.add(value); } value = l; } }
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException { if (var == null) { throw new MissingAttributeException( "var" ); } if (select == null) { throw new MissingAttributeException( "select" ); } Object xpathContext = getXPathContext(); Object value = null; try { if(single!=null && single.booleanValue()==true) { value = select.selectSingleNode(xpathContext); } else { value = select.evaluate(xpathContext); } } catch (JaxenException e) { throw new JellyTagException(e); } if (value instanceof List) { // sort the list if xpCmp is set. if (xpCmp != null && (xpCmp.getXpath() != null)) { Collections.sort((List)value, xpCmp); } } switch ( determineReturnType() ) { case RETURN_NODE_LIST: value = valueAsList(value); break; case RETURN_FIRST_NODE: value = valueAsSingle(value); break; case RETURN_STRING_LIST: value = nodeListToStringList(valueAsList(value)); break; case RETURN_DELIMITED_STRING_LIST: value = joinDelimitedElements(nodeListToStringList(valueAsList(value))); break; case RETURN_FIRST_AS_STRING: value = singleValueAsString(valueAsSingle(value)); break; } //log.info( "Evaluated xpath: " + select + " as: " + value + " of type: " + value.getClass().getName() ); context.setVariable(var, value); }
if(asString != null && asString.booleanValue()) { if(value instanceof Node) { value = ((Node) value).getStringValue(); } else if(value instanceof List) { for(ListIterator it = ((List) value).listIterator(); it.hasNext(); ) { Object v = it.next(); if(v instanceof Node) { v = ((Node) v).getStringValue(); it.set(v); } } } } if(delimiter != null && value instanceof List) { StringBuffer buff = new StringBuffer(); for(Iterator it = ((List) value).iterator(); it.hasNext(); ) { Object v = it.next(); if (v instanceof Node) { buff.append( ((Node) v).getStringValue()); } else { buff.append(v.toString()); } if(it.hasNext()) { buff.append(delimiter); } } buff.setLength(buff.length()); value = buff.toString(); }
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException { if (var == null) { throw new MissingAttributeException( "var" ); } if (select == null) { throw new MissingAttributeException( "select" ); } Object xpathContext = getXPathContext(); Object value = null; try { if(single!=null && single.booleanValue()==true) { value = select.selectSingleNode(xpathContext); } else { value = select.evaluate(xpathContext); } } catch (JaxenException e) { throw new JellyTagException(e); } if (value instanceof List) { // sort the list if xpCmp is set. if (xpCmp != null && (xpCmp.getXpath() != null)) { Collections.sort((List)value, xpCmp); } } switch ( determineReturnType() ) { case RETURN_NODE_LIST: value = valueAsList(value); break; case RETURN_FIRST_NODE: value = valueAsSingle(value); break; case RETURN_STRING_LIST: value = nodeListToStringList(valueAsList(value)); break; case RETURN_DELIMITED_STRING_LIST: value = joinDelimitedElements(nodeListToStringList(valueAsList(value))); break; case RETURN_FIRST_AS_STRING: value = singleValueAsString(valueAsSingle(value)); break; } //log.info( "Evaluated xpath: " + select + " as: " + value + " of type: " + value.getClass().getName() ); context.setVariable(var, value); }
this.delim = delim;
this.delimiter = delim; if( delim!=null ) { this.asString = Boolean.TRUE; }
public void setDelim(String delim) { this.delim = delim; }
logger.debug("dbChildrenInserted SQLObjectEvent: "+e);
if (logger.isDebugEnabled()) { logger.debug("dbChildrenInserted SQLObjectEvent: "+e +"; tree path="+Arrays.asList(getPathToNode(e.getSQLSource()))); }
public void dbChildrenInserted(SQLObjectEvent e) { logger.debug("dbChildrenInserted SQLObjectEvent: "+e); try { SQLObject[] newEventSources = e.getChildren(); for (int i = 0; i < newEventSources.length; i++) { ArchitectUtils.listenToHierarchy(this, newEventSources[i]); } } catch (ArchitectException ex) { logger.error("Error listening to added object", ex); } TreeModelEvent tme = new TreeModelEvent(this, getPathToNode(e.getSQLSource()), e.getChangedIndices(), e.getChildren()); fireTreeNodesInserted(tme); }
logger.debug("dbChildrenRemoved SQLObjectEvent: "+e);
if (logger.isDebugEnabled()) logger.debug("dbChildrenRemoved SQLObjectEvent: "+e);
public void dbChildrenRemoved(SQLObjectEvent e) { logger.debug("dbChildrenRemoved SQLObjectEvent: "+e); try { SQLObject[] oldEventSources = e.getChildren(); for (int i = 0; i < oldEventSources.length; i++) { ArchitectUtils.unlistenToHierarchy(this, oldEventSources[i]); } } catch (ArchitectException ex) { logger.error("Error unlistening to removed object", ex); } TreeModelEvent tme = new TreeModelEvent(this, getPathToNode(e.getSQLSource()), e.getChangedIndices(), e.getChildren()); fireTreeNodesRemoved(tme); }
logger.debug("dbObjectChanged SQLObjectEvent: "+e);
if (logger.isDebugEnabled()) logger.debug("dbObjectChanged SQLObjectEvent: "+e);
public void dbObjectChanged(SQLObjectEvent e) { logger.debug("dbObjectChanged SQLObjectEvent: "+e); SQLObject source = e.getSQLSource(); fireTreeNodesChanged(new TreeModelEvent(this, getPathToNode(source))); }
logger.debug("Firing treeNodesInserted event: "+e);
if (logger.isDebugEnabled()) logger.debug("Firing treeNodesInserted event: "+e);
protected void fireTreeNodesInserted(TreeModelEvent e) { logger.debug("Firing treeNodesInserted event: "+e); Iterator it = treeModelListeners.iterator(); while (it.hasNext()) { ((TreeModelListener) it.next()).treeNodesInserted(e); } }
logger.debug("Firing treeNodesRemoved event "+e);
if (logger.isDebugEnabled()) logger.debug("Firing treeNodesRemoved event "+e);
protected void fireTreeNodesRemoved(TreeModelEvent e) { logger.debug("Firing treeNodesRemoved event "+e); Iterator it = treeModelListeners.iterator(); while (it.hasNext()) { ((TreeModelListener) it.next()).treeNodesRemoved(e); logger.debug("Sent a copy"); } }
logger.debug("Sent a copy");
if (logger.isDebugEnabled()) logger.debug("Sent a copy");
protected void fireTreeNodesRemoved(TreeModelEvent e) { logger.debug("Firing treeNodesRemoved event "+e); Iterator it = treeModelListeners.iterator(); while (it.hasNext()) { ((TreeModelListener) it.next()).treeNodesRemoved(e); logger.debug("Sent a copy"); } }
logger.debug("DBTreeModel.getChild("+parent+","+index+"): returning "+((SQLObject) parent).getChild(index));
if (logger.isDebugEnabled()) logger.debug("DBTreeModel.getChild("+parent+","+index+"): returning "+((SQLObject) parent).getChild(index));
public Object getChild(Object parent, int index) { try { logger.debug("DBTreeModel.getChild("+parent+","+index+"): returning "+((SQLObject) parent).getChild(index)); return ((SQLObject) parent).getChild(index); } catch (ArchitectException e) { //logger.error("Couldn't get child "+index+" of "+parent, e); //return null; throw new ArchitectRuntimeException(e); } }
logger.debug("DBTreeModel.getChildCount("+parent+"): returning "+((SQLObject) parent).getChildCount());
if (logger.isDebugEnabled()) logger.debug("DBTreeModel.getChildCount("+parent+"): returning "+((SQLObject) parent).getChildCount());
public int getChildCount(Object parent) { try { logger.debug("DBTreeModel.getChildCount("+parent+"): returning "+((SQLObject) parent).getChildCount()); return ((SQLObject) parent).getChildCount(); } catch (ArchitectException e) { //logger.error("Couldn't get child count of "+parent, e); //return -1; throw new ArchitectRuntimeException(e); } }
logger.debug("DBTreeModel.getIndexOfChild("+parent+","+child+"): returning "+((SQLObject) parent).getChildren().indexOf(child));
if (logger.isDebugEnabled()) logger.debug("DBTreeModel.getIndexOfChild("+parent+","+child+"): returning "+((SQLObject) parent).getChildren().indexOf(child));
public int getIndexOfChild(Object parent, Object child) { try { logger.debug("DBTreeModel.getIndexOfChild("+parent+","+child+"): returning "+((SQLObject) parent).getChildren().indexOf(child)); return ((SQLObject) parent).getChildren().indexOf(child); } catch (ArchitectException e) { //logger.error("Couldn't get index of child "+child, e); //return -1; throw new ArchitectRuntimeException(e); } }
logger.debug("DBTreeModel.getRoot: returning "+root);
if (logger.isDebugEnabled()) logger.debug("DBTreeModel.getRoot: returning "+root);
public Object getRoot() { logger.debug("DBTreeModel.getRoot: returning "+root); return root; }
logger.debug("DBTreeModel.isLeaf("+parent+"): returning "+!((SQLObject) parent).allowsChildren());
if (logger.isDebugEnabled()) logger.debug("DBTreeModel.isLeaf("+parent+"): returning "+!((SQLObject) parent).allowsChildren());
public boolean isLeaf(Object parent) { logger.debug("DBTreeModel.isLeaf("+parent+"): returning "+!((SQLObject) parent).allowsChildren()); return !((SQLObject) parent).allowsChildren(); }
String appType = config.getType(); if (appType.equals("connector")) { create(config);
if (config.isCluster()) { List<ApplicationConfig> clusterApps = config.getApplications(); for(ApplicationConfig clusterConfig : clusterApps) { load(clusterConfig); } } else { load(config);
public static void load() throws Exception { List<ApplicationConfig> applications = ApplicationConfigManager.getApplications(); for(ApplicationConfig config : applications) { String appType = config.getType(); if (appType.equals("connector")) { create(config); } } }
String namespaceURI, String localName, String qName,
final String namespaceURI, final String localName, final String qName,
protected TagScript createStaticTag( String namespaceURI, String localName, String qName, Attributes list) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName, qName); StaticTagScript script = new StaticTagScript(tag); // now iterate through through the expressions int size = list.getLength(); for (int i = 0; i < size; i++) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = CompositeExpression.parse( attributeValue, getExpressionFactory() ); script.addAttribute(attributeName, expression); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e); throw createSAXException(e); } }
StaticTag tag = new StaticTag( namespaceURI, localName, qName); StaticTagScript script = new StaticTagScript(tag);
StaticTag tag = new StaticTag( namespaceURI, localName, qName ); StaticTagScript script = new StaticTagScript( new TagFactory() { public Tag createTag() { return new StaticTag( namespaceURI, localName, qName ); } } );
protected TagScript createStaticTag( String namespaceURI, String localName, String qName, Attributes list) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName, qName); StaticTagScript script = new StaticTagScript(tag); // now iterate through through the expressions int size = list.getLength(); for (int i = 0; i < size; i++) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = CompositeExpression.parse( attributeValue, getExpressionFactory() ); script.addAttribute(attributeName, expression); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e); throw createSAXException(e); } }
int size = tagStack.size(); if ( size <= 0 ) { parentTag = null; } else { parentTag = (Tag) tagStack.remove( size - 1 ); }
if ( tagScriptStack.isEmpty() ) { tagScript = null; } else { tagScript = (TagScript) tagScriptStack.get(tagScriptStack.size() - 1); }
public void endElement(String namespaceURI, String localName, String qName) throws SAXException { try { tagScript = (TagScript) tagScriptStack.remove(tagScriptStack.size() - 1); if (tagScript != null) { if (textBuffer.length() > 0) { addTextScript(textBuffer.toString()); textBuffer.setLength(0); } script = (ScriptBlock) scriptStack.pop(); } else { textBuffer.append("</"); textBuffer.append(qName); textBuffer.append(">"); } int size = tagStack.size(); if ( size <= 0 ) { parentTag = null; } else { parentTag = (Tag) tagStack.remove( size - 1 ); } } catch (SAXException e) { throw e; } catch (Exception e) { log.error( "Caught exception: " + e, e ); throw new SAXException( "Runtime Exception: " + e, e ); } }
parentTag = null;
public void startDocument() throws SAXException { script = new ScriptBlock(); textBuffer = new StringBuffer(); tagScript = null; parentTag = null; scriptStack.clear(); tagScriptStack.clear(); }
Tag tag = tagScript.getTag(); tag.setParent(parentTag);
tagScript.setParent(parentTagScript);
public void startElement( String namespaceURI, String localName, String qName, Attributes list) throws SAXException { try { // add check to ensure namespace URI is "" for no namespace if ( namespaceURI == null ) { namespaceURI = ""; } // if this is a tag then create a script to run it // otherwise pass the text to the current body tagScript = createTag(namespaceURI, localName, list); if (tagScript == null) { tagScript = createStaticTag(namespaceURI, localName, qName, list); } tagScriptStack.add(tagScript); if (tagScript != null) { // set parent relationship... Tag tag = tagScript.getTag(); tag.setParent(parentTag); // set the namespace Map if ( elementNamespaces != null ) { tagScript.setNamespacesMap( elementNamespaces ); elementNamespaces = null; } // set the line number details if ( locator != null ) { tagScript.setLocator(locator); } // sets the file name element names tagScript.setFileName(fileName); tagScript.setElementName(qName); // pop another tag onto the stack if ( parentTag != null ) { tagStack.add( parentTag ); } parentTag = tag; if (textBuffer.length() > 0) { addTextScript(textBuffer.toString()); textBuffer.setLength(0); } script.addScript(tagScript); // start a new body scriptStack.push(script); script = new ScriptBlock(); tag.setBody(script); } else { // XXXX: might wanna handle empty elements later... textBuffer.append("<"); textBuffer.append(qName); int size = list.getLength(); for (int i = 0; i < size; i++) { textBuffer.append(" "); textBuffer.append(list.getQName(i)); textBuffer.append("="); textBuffer.append("\""); textBuffer.append(list.getValue(i)); textBuffer.append("\""); } textBuffer.append(">"); } } catch (SAXException e) { throw e; } catch (Exception e) { log.error( "Caught exception: " + e, e ); throw new SAXException( "Runtime Exception: " + e, e ); } }
if ( parentTag != null ) { tagStack.add( parentTag ); } parentTag = tag;
public void startElement( String namespaceURI, String localName, String qName, Attributes list) throws SAXException { try { // add check to ensure namespace URI is "" for no namespace if ( namespaceURI == null ) { namespaceURI = ""; } // if this is a tag then create a script to run it // otherwise pass the text to the current body tagScript = createTag(namespaceURI, localName, list); if (tagScript == null) { tagScript = createStaticTag(namespaceURI, localName, qName, list); } tagScriptStack.add(tagScript); if (tagScript != null) { // set parent relationship... Tag tag = tagScript.getTag(); tag.setParent(parentTag); // set the namespace Map if ( elementNamespaces != null ) { tagScript.setNamespacesMap( elementNamespaces ); elementNamespaces = null; } // set the line number details if ( locator != null ) { tagScript.setLocator(locator); } // sets the file name element names tagScript.setFileName(fileName); tagScript.setElementName(qName); // pop another tag onto the stack if ( parentTag != null ) { tagStack.add( parentTag ); } parentTag = tag; if (textBuffer.length() > 0) { addTextScript(textBuffer.toString()); textBuffer.setLength(0); } script.addScript(tagScript); // start a new body scriptStack.push(script); script = new ScriptBlock(); tag.setBody(script); } else { // XXXX: might wanna handle empty elements later... textBuffer.append("<"); textBuffer.append(qName); int size = list.getLength(); for (int i = 0; i < size; i++) { textBuffer.append(" "); textBuffer.append(list.getQName(i)); textBuffer.append("="); textBuffer.append("\""); textBuffer.append(list.getValue(i)); textBuffer.append("\""); } textBuffer.append(">"); } } catch (SAXException e) { throw e; } catch (Exception e) { log.error( "Caught exception: " + e, e ); throw new SAXException( "Runtime Exception: " + e, e ); } }
tag.setBody(script);
tagScript.setTagBody(script);
public void startElement( String namespaceURI, String localName, String qName, Attributes list) throws SAXException { try { // add check to ensure namespace URI is "" for no namespace if ( namespaceURI == null ) { namespaceURI = ""; } // if this is a tag then create a script to run it // otherwise pass the text to the current body tagScript = createTag(namespaceURI, localName, list); if (tagScript == null) { tagScript = createStaticTag(namespaceURI, localName, qName, list); } tagScriptStack.add(tagScript); if (tagScript != null) { // set parent relationship... Tag tag = tagScript.getTag(); tag.setParent(parentTag); // set the namespace Map if ( elementNamespaces != null ) { tagScript.setNamespacesMap( elementNamespaces ); elementNamespaces = null; } // set the line number details if ( locator != null ) { tagScript.setLocator(locator); } // sets the file name element names tagScript.setFileName(fileName); tagScript.setElementName(qName); // pop another tag onto the stack if ( parentTag != null ) { tagStack.add( parentTag ); } parentTag = tag; if (textBuffer.length() > 0) { addTextScript(textBuffer.toString()); textBuffer.setLength(0); } script.addScript(tagScript); // start a new body scriptStack.push(script); script = new ScriptBlock(); tag.setBody(script); } else { // XXXX: might wanna handle empty elements later... textBuffer.append("<"); textBuffer.append(qName); int size = list.getLength(); for (int i = 0; i < size; i++) { textBuffer.append(" "); textBuffer.append(list.getQName(i)); textBuffer.append("="); textBuffer.append("\""); textBuffer.append(list.getValue(i)); textBuffer.append("\""); } textBuffer.append(">"); } } catch (SAXException e) { throw e; } catch (Exception e) { log.error( "Caught exception: " + e, e ); throw new SAXException( "Runtime Exception: " + e, e ); } }
System.out.println( "Created list: " + list + " with items: " + items );
protected void processBean(String var, Object bean) throws Exception { super.processBean(var, bean); List list = getList(); System.out.println( "Created list: " + list + " with items: " + items ); // if the items variable is specified lets append all the items if (items != null) { Iterator iter = items.evaluateAsIterator(context); while (iter.hasNext()) { list.add( iter.next() ); } } }
Object value = attributes.remove("items"); System.out.println( "value: " + value );
items = (Expression) attributes.remove("items");
protected void setBeanProperties(Object bean, Map attributes) throws Exception { Object value = attributes.remove("items"); System.out.println( "value: " + value ); super.setBeanProperties(bean, attributes); // #### @todo use same algorithm as evaluateAsIterator() List list = getList(); if (value instanceof Iterator) { Iterator iter = (Iterator) value; while (iter.hasNext()) { list.add( iter.next() ); } } }
List list = getList(); if (value instanceof Iterator) { Iterator iter = (Iterator) value; while (iter.hasNext()) { list.add( iter.next() ); } }
protected void setBeanProperties(Object bean, Map attributes) throws Exception { Object value = attributes.remove("items"); System.out.println( "value: " + value ); super.setBeanProperties(bean, attributes); // #### @todo use same algorithm as evaluateAsIterator() List list = getList(); if (value instanceof Iterator) { Iterator iter = (Iterator) value; while (iter.hasNext()) { list.add( iter.next() ); } } }
registerBeanFactory( "dialog", JDesktopPane.class );
registerBeanFactory( "dialog", JDialog.class ); registerBeanFactory( "fileChooser", JFileChooser.class );
protected void registerFactories() { registerBeanFactory( "button", JButton.class ); registerBeanFactory( "checkBox", JCheckBox.class ); registerBeanFactory( "checkBoxMenuItem", JCheckBoxMenuItem.class ); registerBeanFactory( "comboBox", JComboBox.class ); // how to add content there ? // Have a ComboBoxModel (just one should have a Table or Tree Model objects) ? // can the element control it's children ? // but children should also be able to be any component (as Swing comps. are all container) registerBeanFactory( "desktopPane", JDesktopPane.class ); registerBeanFactory( "dialog", JDesktopPane.class ); registerBeanFactory( "frame", JFrame.class ); registerBeanFactory( "internalFrame", JInternalFrame.class ); registerBeanFactory( "label", JLabel.class ); registerBeanFactory( "list", JList.class ); registerBeanFactory( "menu", JMenu.class ); registerBeanFactory( "menuBar", JMenuBar.class ); registerBeanFactory( "menuItem", JMenuItem.class ); registerBeanFactory( "panel", JPanel.class ); registerBeanFactory( "passwordField", JPasswordField.class ); registerBeanFactory( "popupMenu", JPopupMenu.class ); registerBeanFactory( "radioButton", JRadioButton.class ); registerBeanFactory( "radioButtonMenuItem", JRadioButtonMenuItem.class ); registerBeanFactory( "optionPane", JOptionPane.class ); registerBeanFactory( "scrollPane", JScrollPane.class ); registerBeanFactory( "separator", JSeparator.class ); registerFactory( "splitPane", new Factory() { public Object newInstance() { JSplitPane answer = new JSplitPane(); answer.setLeftComponent(null); answer.setRightComponent(null); answer.setTopComponent(null); answer.setBottomComponent(null); return answer; } } ); registerBeanFactory( "tabbedPane", JTabbedPane.class ); registerBeanFactory( "table", JTable.class ); registerBeanFactory( "textArea", JTextArea.class ); registerBeanFactory( "textField", JTextField.class ); registerBeanFactory( "toggleButton", JToggleButton.class ); registerBeanFactory( "tree", JTree.class ); registerBeanFactory( "toolBar", JToolBar.class ); }
root.addChild(root.getChildCount(), new SQLDatabase(dbcs));
if (dbcsAlreadyExists(dbcs)) { logger.warn("database already exists in this project."); JOptionPane.showMessageDialog(DBTree.this, "Can't add connection, connection already exists in this project.", "Warning", JOptionPane.WARNING_MESSAGE); } else { root.addChild(root.getChildCount(), new SQLDatabase(dbcs)); }
public void actionPerformed(ActionEvent e) { SQLObject root = (SQLObject) getModel().getRoot(); try { root.addChild(root.getChildCount(), new SQLDatabase(dbcs)); } catch (ArchitectException ex) { logger.warn("Couldn't add new database to tree", ex); JOptionPane.showMessageDialog(DBTree.this, "Couldn't add new connection:\n"+ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }
refreshDBCSMenu(); TreePath p = getPathForLocation(e.getX(), e.getY());
TreePath p = getPathForLocation(e.getX(), e.getY()); refreshDBCSMenu(isTargetDatabaseNode(p));
private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { refreshDBCSMenu(); TreePath p = getPathForLocation(e.getX(), e.getY()); if (p == null) { popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(false); popup.getComponent(2).setVisible(false); } else { //SQLObject so = (SQLObject) p.getLastPathComponent(); popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(true); popup.getComponent(2).setVisible(true); } setSelectionPath(p); popup.show(e.getComponent(), e.getX(), e.getY()); } }
popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(false); popup.getComponent(2).setVisible(false);
logger.debug("not over anything, so give NEW option"); popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(false);
private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { refreshDBCSMenu(); TreePath p = getPathForLocation(e.getX(), e.getY()); if (p == null) { popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(false); popup.getComponent(2).setVisible(false); } else { //SQLObject so = (SQLObject) p.getLastPathComponent(); popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(true); popup.getComponent(2).setVisible(true); } setSelectionPath(p); popup.show(e.getComponent(), e.getX(), e.getY()); } }
popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(true); popup.getComponent(2).setVisible(true);
popup.getComponent(0).setVisible(isTargetDatabaseNode(p)); popup.getComponent(1).setVisible(true);
private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { refreshDBCSMenu(); TreePath p = getPathForLocation(e.getX(), e.getY()); if (p == null) { popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(false); popup.getComponent(2).setVisible(false); } else { //SQLObject so = (SQLObject) p.getLastPathComponent(); popup.getComponent(0).setVisible(true); popup.getComponent(1).setVisible(true); popup.getComponent(2).setVisible(true); } setSelectionPath(p); popup.show(e.getComponent(), e.getX(), e.getY()); } }
protected void refreshDBCSMenu() { popupDBCSMenu.removeAll(); popupDBCSMenu.add(new JMenuItem(newDBCSAction)); popupDBCSMenu.addSeparator();
protected void refreshDBCSMenu(boolean suppressNew) { logger.debug("refreshDBCSMenu is being called."); popupDBCSMenu.removeAll(); if (!suppressNew) { popupDBCSMenu.add(new JMenuItem(newDBCSAction)); popupDBCSMenu.addSeparator(); }
protected void refreshDBCSMenu() { popupDBCSMenu.removeAll(); popupDBCSMenu.add(new JMenuItem(newDBCSAction)); popupDBCSMenu.addSeparator(); Iterator it = ArchitectFrame.getMainInstance().getUserSettings().getConnections().iterator(); while(it.hasNext()) { DBConnectionSpec dbcs = (DBConnectionSpec) it.next(); popupDBCSMenu.add(new JMenuItem(new AddDBCSAction(dbcs))); } }
popupDBCSMenu.add(new JMenuItem(new AddDBCSAction(dbcs)));
if (!suppressNew) { popupDBCSMenu.setText("Add Connection"); popupDBCSMenu.add(new JMenuItem(new AddDBCSAction(dbcs))); } else { popupDBCSMenu.setText("Set Target Database"); popupDBCSMenu.add(new JMenuItem(new setTargetDBCSAction(dbcs))); }
protected void refreshDBCSMenu() { popupDBCSMenu.removeAll(); popupDBCSMenu.add(new JMenuItem(newDBCSAction)); popupDBCSMenu.addSeparator(); Iterator it = ArchitectFrame.getMainInstance().getUserSettings().getConnections().iterator(); while(it.hasNext()) { DBConnectionSpec dbcs = (DBConnectionSpec) it.next(); popupDBCSMenu.add(new JMenuItem(new AddDBCSAction(dbcs))); } }
newMenu.add(popupDBCSMenu = new JMenu("Add Connection")); newMenu.addSeparator();
newMenu.add(popupDBCSMenu = new JMenu("Add Connection"));
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 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); } return newMenu; }
assertFalse(sourceLoadRadio.isEnabled());
public void testDisableSourceDatabaseComponents() { JFrame frame = new JFrame(); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); assertFalse(sourceDatabaseDropdown.isEnabled()); assertFalse(sourceNewConnButton.isEnabled()); assertFalse(sourceCatalogDropdown.isEnabled()); assertFalse(sourceSchemaDropdown.isEnabled()); assertFalse(sourceLoadRadio.isEnabled()); assertFalse(sourceLoadFilePath.isEnabled()); assertFalse(sourceLoadFileButton.isEnabled()); flushAWT(); // Select the database drop down // This is not the point of the test but has to be done Point p = sourcePhysicalRadio.getLocationOnScreen(); robot.mouseMove(p.x, p.y); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); flushAWT(); assertTrue(sourceDatabaseDropdown.isEnabled()); assertTrue(sourceNewConnButton.isEnabled()); assertFalse(sourceCatalogDropdown.isEnabled()); assertFalse(sourceSchemaDropdown.isEnabled()); p = sourcePlayPenRadio.getLocationOnScreen(); robot.mouseMove(p.x, p.y); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); flushAWT(); assertFalse(sourceDatabaseDropdown.isEnabled()); assertFalse(sourceNewConnButton.isEnabled()); assertFalse(sourceCatalogDropdown.isEnabled()); assertFalse(sourceSchemaDropdown.isEnabled()); frame.dispose(); }
String infoMaybe ="";
String infoMaybe =null;
private void doBatch() { Vector files; File batchFile; File dataFile; String line; StringTokenizer tok; String infoMaybe =""; files = new Vector(); if(batchFileName == null) { return; } batchFile = new File(this.batchFileName); if(!batchFile.exists()) { System.out.println("batch file " + batchFileName + " does not exist"); System.exit(1); } if (!quietMode) System.out.println("Processing batch input file: " + batchFile); try { BufferedReader br = new BufferedReader(new FileReader(batchFile)); while( (line = br.readLine()) != null ) { files.add(line); } br.close(); for(int i = 0;i<files.size();i++){ line = (String)files.get(i); tok = new StringTokenizer(line); infoMaybe = ""; if(tok.hasMoreTokens()){ dataFile = new File(tok.nextToken()); if(tok.hasMoreTokens()){ infoMaybe = tok.nextToken(); } if(dataFile.exists()) { String name = dataFile.getName(); if( name.substring(name.length()-4,name.length()).equalsIgnoreCase(".ped") ) { processFile(name,PED_FILE,infoMaybe); } else if(name.substring(name.length()-5,name.length()).equalsIgnoreCase(".haps")) { processFile(name,HAPS_FILE,infoMaybe); } else if(name.substring(name.length()-4,name.length()).equalsIgnoreCase(".hmp")){ processFile(name,HMP_FILE,""); } else{ if (!quietMode){ System.out.println("Filenames in batch file must end in .ped, .haps or .hmp\n" + name + " is not properly formatted."); } } } else { if(!quietMode){ System.out.println("file " + dataFile.getName() + " listed in the batch file could not be found"); } } } } } catch(FileNotFoundException e){ System.out.println("the following error has occured:\n" + e.toString()); } catch(IOException e){ System.out.println("the following error has occured:\n" + e.toString()); } }
infoMaybe = "";
infoMaybe = null;
private void doBatch() { Vector files; File batchFile; File dataFile; String line; StringTokenizer tok; String infoMaybe =""; files = new Vector(); if(batchFileName == null) { return; } batchFile = new File(this.batchFileName); if(!batchFile.exists()) { System.out.println("batch file " + batchFileName + " does not exist"); System.exit(1); } if (!quietMode) System.out.println("Processing batch input file: " + batchFile); try { BufferedReader br = new BufferedReader(new FileReader(batchFile)); while( (line = br.readLine()) != null ) { files.add(line); } br.close(); for(int i = 0;i<files.size();i++){ line = (String)files.get(i); tok = new StringTokenizer(line); infoMaybe = ""; if(tok.hasMoreTokens()){ dataFile = new File(tok.nextToken()); if(tok.hasMoreTokens()){ infoMaybe = tok.nextToken(); } if(dataFile.exists()) { String name = dataFile.getName(); if( name.substring(name.length()-4,name.length()).equalsIgnoreCase(".ped") ) { processFile(name,PED_FILE,infoMaybe); } else if(name.substring(name.length()-5,name.length()).equalsIgnoreCase(".haps")) { processFile(name,HAPS_FILE,infoMaybe); } else if(name.substring(name.length()-4,name.length()).equalsIgnoreCase(".hmp")){ processFile(name,HMP_FILE,""); } else{ if (!quietMode){ System.out.println("Filenames in batch file must end in .ped, .haps or .hmp\n" + name + " is not properly formatted."); } } } else { if(!quietMode){ System.out.println("file " + dataFile.getName() + " listed in the batch file could not be found"); } } } } } catch(FileNotFoundException e){ System.out.println("the following error has occured:\n" + e.toString()); } catch(IOException e){ System.out.println("the following error has occured:\n" + e.toString()); } }
if ( answer == null ) { try { answer = System.getProperty(name); } catch (Throwable t) { }
} if ( answer == null ) { try { answer = System.getProperty(name); } catch (Throwable t) {
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 (Throwable t) { // ignore security exceptions } } } return answer; }
registerTag("run", RunTestTag.class ); registerTag("case", TestCaseTag.class ); registerTag("suite", TestSuiteTag.class );
registerTag("run", RunTag.class ); registerTag("case", CaseTag.class ); registerTag("suite", SuiteTag.class );
public JUnitTagLibrary() { registerTag("assert", AssertTag.class); registerTag("assertEquals", AssertEqualsTag.class); registerTag("fail", FailTag.class); registerTag("run", RunTestTag.class ); registerTag("case", TestCaseTag.class ); registerTag("suite", TestSuiteTag.class ); }
(!mFeatures.contains(MasterFeature.UPDATE_FULL)))
(!mFeatures.contains(MasterFeature.UPDATE_FULL)) && (!mFeatures.contains(MasterFeature.UPDATE_TXN)))
private void generateClass() throws SupportException { // Declare some types. final TypeDesc storableType = TypeDesc.forClass(Storable.class); final TypeDesc triggerSupportType = TypeDesc.forClass(TriggerSupport.class); final TypeDesc masterSupportType = TypeDesc.forClass(MasterSupport.class); final TypeDesc transactionType = TypeDesc.forClass(Transaction.class); final TypeDesc optimisticLockType = TypeDesc.forClass(OptimisticLockException.class); final TypeDesc persistExceptionType = TypeDesc.forClass(PersistException.class); // Add constructor that accepts a MasterSupport. { TypeDesc[] params = {masterSupportType}; MethodInfo mi = mClassFile.addConstructor(Modifiers.PUBLIC, params); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.loadLocal(b.getParameter(0)); b.invokeSuperConstructor(new TypeDesc[] {triggerSupportType}); b.returnVoid(); } // Declare protected abstract methods. { MethodInfo mi = mClassFile.addMethod (Modifiers.PROTECTED.toAbstract(true), DO_TRY_INSERT_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(persistExceptionType); mi = mClassFile.addMethod (Modifiers.PROTECTED.toAbstract(true), DO_TRY_UPDATE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(persistExceptionType); mi = mClassFile.addMethod (Modifiers.PROTECTED.toAbstract(true), DO_TRY_DELETE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(persistExceptionType); } // Add required protected doTryInsert method. { // If sequence support requested, implement special insert hook to // call sequences for properties which are UNINITIALIZED. User may // provide explicit values for properties with sequences. if (mFeatures.contains(MasterFeature.INSERT_SEQUENCES)) { MethodInfo mi = mClassFile.addMethod (Modifiers.PROTECTED, StorableGenerator.CHECK_PK_FOR_INSERT_METHOD_NAME, null, null); CodeBuilder b = new CodeBuilder(mi); int ordinal = 0; for (StorableProperty<S> property : mAllProperties.values()) { if (property.getSequenceName() != null) { // Check the state of this property, to see if it is // uninitialized. Uninitialized state has value zero. String stateFieldName = StorableGenerator.PROPERTY_STATE_FIELD_NAME + (ordinal >> 4); b.loadThis(); b.loadField(stateFieldName, TypeDesc.INT); int shift = (ordinal & 0xf) * 2; b.loadConstant(StorableGenerator.PROPERTY_STATE_MASK << shift); b.math(Opcode.IAND); Label isInitialized = b.createLabel(); b.ifZeroComparisonBranch(isInitialized, "!="); // Load this in preparation for storing value to property. b.loadThis(); // Call MasterSupport.getSequenceValueProducer(String). TypeDesc seqValueProdType = TypeDesc.forClass(SequenceValueProducer.class); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(masterSupportType); b.loadConstant(property.getSequenceName()); b.invokeInterface (masterSupportType, "getSequenceValueProducer", seqValueProdType, new TypeDesc[] {TypeDesc.STRING}); // Find appropriate method to call for getting next sequence value. TypeDesc propertyType = TypeDesc.forClass(property.getType()); TypeDesc propertyObjType = propertyType.toObjectType(); Method method; try { if (propertyObjType == TypeDesc.LONG.toObjectType()) { method = SequenceValueProducer.class .getMethod("nextLongValue", (Class[]) null); } else if (propertyObjType == TypeDesc.INT.toObjectType()) { method = SequenceValueProducer.class .getMethod("nextIntValue", (Class[]) null); } else if (propertyObjType == TypeDesc.STRING) { method = SequenceValueProducer.class .getMethod("nextDecimalValue", (Class[]) null); } else { throw new SupportException ("Unable to support sequence of type \"" + property.getType().getName() + "\" for property: " + property.getName()); } } catch (NoSuchMethodException e) { Error err = new NoSuchMethodError(); err.initCause(e); throw err; } b.invoke(method); b.convert(TypeDesc.forClass(method.getReturnType()), propertyType); // Store property b.storeField(property.getName(), propertyType); // Set state to dirty. b.loadThis(); b.loadThis(); b.loadField(stateFieldName, TypeDesc.INT); b.loadConstant(StorableGenerator.PROPERTY_STATE_DIRTY << shift); b.math(Opcode.IOR); b.storeField(stateFieldName, TypeDesc.INT); isInitialized.setLocation(); } ordinal++; } // We've tried our best to fill in missing values, now run the // original check method. b.loadThis(); b.invokeSuper(mClassFile.getSuperClassName(), StorableGenerator.CHECK_PK_FOR_INSERT_METHOD_NAME, null, null); b.returnVoid(); } MethodInfo mi = mClassFile.addMethod (Modifiers.PROTECTED.toFinal(true), StorableGenerator.DO_TRY_INSERT_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(persistExceptionType); CodeBuilder b = new CodeBuilder(mi); LocalVariable txnVar = b.createLocalVariable(null, transactionType); Label tryStart = addEnterTransaction(b, INSERT_OP, txnVar); if (mFeatures.contains(MasterFeature.VERSIONING)) { // Only set if uninitialized. b.loadThis(); b.invokeVirtual(StorableGenerator.IS_VERSION_INITIALIZED_METHOD_NAME, TypeDesc.BOOLEAN, null); Label isInitialized = b.createLabel(); b.ifZeroComparisonBranch(isInitialized, "!="); addAdjustVersionProperty(b, null, 1); isInitialized.setLocation(); } if (mFeatures.contains(MasterFeature.INSERT_CHECK_REQUIRED)) { // Ensure that required properties have been set. b.loadThis(); b.invokeVirtual(StorableGenerator.IS_REQUIRED_DATA_INITIALIZED_METHOD_NAME, TypeDesc.BOOLEAN, null); Label isInitialized = b.createLabel(); b.ifZeroComparisonBranch(isInitialized, "!="); // Throw a ConstraintException. TypeDesc exType = TypeDesc.forClass(ConstraintException.class); b.newObject(exType); b.dup(); // Append all the uninitialized property names to the exception message. LocalVariable countVar = b.createLocalVariable(null, TypeDesc.INT); b.loadConstant(0); b.storeLocal(countVar); TypeDesc sbType = TypeDesc.forClass(StringBuilder.class); b.newObject(sbType); b.dup(); b.loadConstant("Not all required properties have been set: "); TypeDesc[] stringParam = {TypeDesc.STRING}; b.invokeConstructor(sbType, stringParam); LocalVariable sbVar = b.createLocalVariable(null, sbType); b.storeLocal(sbVar); int ordinal = -1; HashSet<Integer> stateAppendMethods = new HashSet<Integer>(); // Parameters are: StringBuilder, count, mask, property name TypeDesc[] appendParams = {sbType, TypeDesc.INT, TypeDesc.INT, TypeDesc.STRING}; for (StorableProperty<S> property : mAllProperties.values()) { ordinal++; if (property.isJoin() || property.isPrimaryKeyMember() || property.isNullable()) { continue; } int stateField = ordinal >> 4; String stateAppendMethodName = APPEND_UNINIT_PROPERTY + stateField; if (!stateAppendMethods.contains(stateField)) { stateAppendMethods.add(stateField); MethodInfo mi2 = mClassFile.addMethod (Modifiers.PRIVATE, stateAppendMethodName, TypeDesc.INT, appendParams); CodeBuilder b2 = new CodeBuilder(mi2); // Load the StringBuilder parameter. b2.loadLocal(b2.getParameter(0)); String stateFieldName = StorableGenerator.PROPERTY_STATE_FIELD_NAME + (ordinal >> 4); b2.loadThis(); b2.loadField(stateFieldName, TypeDesc.INT); // Load the mask parameter. b2.loadLocal(b2.getParameter(2)); b2.math(Opcode.IAND); Label propIsInitialized = b2.createLabel(); b2.ifZeroComparisonBranch(propIsInitialized, "!="); // Load the count parameter. b2.loadLocal(b2.getParameter(1)); Label noComma = b2.createLabel(); b2.ifZeroComparisonBranch(noComma, "=="); b2.loadConstant(", "); b2.invokeVirtual(sbType, "append", sbType, stringParam); noComma.setLocation(); // Load the property name parameter. b2.loadLocal(b2.getParameter(3)); b2.invokeVirtual(sbType, "append", sbType, stringParam); // Increment the count parameter. b2.integerIncrement(b2.getParameter(1), 1); propIsInitialized.setLocation(); // Return the possibly updated count. b2.loadLocal(b2.getParameter(1)); b2.returnValue(TypeDesc.INT); } b.loadThis(); // Parameters are: StringBuilder, count, mask, property name b.loadLocal(sbVar); b.loadLocal(countVar); b.loadConstant(StorableGenerator.PROPERTY_STATE_MASK << ((ordinal & 0xf) * 2)); b.loadConstant(property.getName()); b.invokePrivate(stateAppendMethodName, TypeDesc.INT, appendParams); b.storeLocal(countVar); } b.loadLocal(sbVar); b.invokeVirtual(sbType, "toString", TypeDesc.STRING, null); b.invokeConstructor(exType, new TypeDesc[] {TypeDesc.STRING}); b.throwObject(); isInitialized.setLocation(); } b.loadThis(); b.invokeVirtual(DO_TRY_INSERT_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); if (tryStart == null) { b.returnValue(TypeDesc.BOOLEAN); } else { Label failed = b.createLabel(); b.ifZeroComparisonBranch(failed, "=="); addCommitAndExitTransaction(b, INSERT_OP, txnVar); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); failed.setLocation(); addExitTransaction(b, INSERT_OP, txnVar); b.loadConstant(false); b.returnValue(TypeDesc.BOOLEAN); addExitTransaction(b, INSERT_OP, txnVar, tryStart); } } // Add required protected doTryUpdate method. addDoTryUpdate: { MethodInfo mi = mClassFile.addMethod (Modifiers.PROTECTED.toFinal(true), StorableGenerator.DO_TRY_UPDATE_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(persistExceptionType); CodeBuilder b = new CodeBuilder(mi); if ((!mFeatures.contains(MasterFeature.VERSIONING)) && (!mFeatures.contains(MasterFeature.UPDATE_FULL))) { // Nothing special needs to be done, so just delegate and return. b.loadThis(); b.invokeVirtual(DO_TRY_UPDATE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); b.returnValue(TypeDesc.BOOLEAN); break addDoTryUpdate; } LocalVariable txnVar = b.createLocalVariable(null, transactionType); LocalVariable savedVar = null; Label tryStart = addEnterTransaction(b, UPDATE_OP, txnVar); Label failed = b.createLabel(); if (mFeatures.contains(MasterFeature.UPDATE_FULL)) { // Storable saved = copy(); b.loadThis(); b.invokeVirtual(COPY_METHOD_NAME, storableType, null); b.checkCast(mClassFile.getType()); savedVar = b.createLocalVariable(null, mClassFile.getType()); b.storeLocal(savedVar); // if (!saved.tryLoad()) { // goto failed; // } b.loadLocal(savedVar); b.invokeInterface(storableType, TRY_LOAD_METHOD_NAME, TypeDesc.BOOLEAN, null); b.ifZeroComparisonBranch(failed, "=="); // if (version support enabled) { // if (this.getVersionNumber() != saved.getVersionNumber()) { // throw new OptimisticLockException // (this.getVersionNumber(), saved.getVersionNumber(), this); // } // } if (mFeatures.contains(MasterFeature.VERSIONING)) { TypeDesc versionType = TypeDesc.forClass(mInfo.getVersionProperty().getType()); b.loadThis(); b.invoke(mInfo.getVersionProperty().getReadMethod()); b.loadLocal(savedVar); b.invoke(mInfo.getVersionProperty().getReadMethod()); Label sameVersion = b.createLabel(); CodeBuilderUtil.addValuesEqualCall(b, versionType, true, sameVersion, true); b.newObject(optimisticLockType); b.dup(); b.loadThis(); b.invoke(mInfo.getVersionProperty().getReadMethod()); b.convert(versionType, TypeDesc.OBJECT); b.loadLocal(savedVar); b.invoke(mInfo.getVersionProperty().getReadMethod()); b.convert(versionType, TypeDesc.OBJECT); b.loadThis(); b.invokeConstructor (optimisticLockType, new TypeDesc[] {TypeDesc.OBJECT, TypeDesc.OBJECT, storableType}); b.throwObject(); sameVersion.setLocation(); } // this.copyDirtyProperties(saved); // if (version support enabled) { // saved.setVersionNumber(saved.getVersionNumber() + 1); // } b.loadThis(); b.loadLocal(savedVar); b.invokeVirtual(COPY_DIRTY_PROPERTIES, null, new TypeDesc[] {storableType}); if (mFeatures.contains(MasterFeature.VERSIONING)) { addAdjustVersionProperty(b, savedVar, -1); } // if (!saved.doTryUpdateMaster()) { // goto failed; // } b.loadLocal(savedVar); b.invokeVirtual(DO_TRY_UPDATE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); b.ifZeroComparisonBranch(failed, "=="); // saved.copyUnequalProperties(this); b.loadLocal(savedVar); b.loadThis(); b.invokeInterface (storableType, COPY_UNEQUAL_PROPERTIES, null, new TypeDesc[] {storableType}); } else { // if (!this.doTryUpdateMaster()) { // goto failed; // } b.loadThis(); b.invokeVirtual(DO_TRY_UPDATE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); b.ifZeroComparisonBranch(failed, "=="); } // txn.commit(); // txn.exit(); // return true; addCommitAndExitTransaction(b, UPDATE_OP, txnVar); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); // failed: // txn.exit(); failed.setLocation(); addExitTransaction(b, UPDATE_OP, txnVar); // return false; b.loadConstant(false); b.returnValue(TypeDesc.BOOLEAN); addExitTransaction(b, UPDATE_OP, txnVar, tryStart); } // Add required protected doTryDelete method. { MethodInfo mi = mClassFile.addMethod (Modifiers.PROTECTED.toFinal(true), StorableGenerator.DO_TRY_DELETE_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(persistExceptionType); CodeBuilder b = new CodeBuilder(mi); LocalVariable txnVar = b.createLocalVariable(null, transactionType); Label tryStart = addEnterTransaction(b, DELETE_OP, txnVar); b.loadThis(); b.invokeVirtual(DO_TRY_DELETE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); if (tryStart == null) { b.returnValue(TypeDesc.BOOLEAN); } else { Label failed = b.createLabel(); b.ifZeroComparisonBranch(failed, "=="); addCommitAndExitTransaction(b, DELETE_OP, txnVar); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); failed.setLocation(); addExitTransaction(b, DELETE_OP, txnVar); b.loadConstant(false); b.returnValue(TypeDesc.BOOLEAN); addExitTransaction(b, DELETE_OP, txnVar, tryStart); } } }
int rColWidth = size.width - lColWidth - ins.left - ins.right;
int rColWidth = size.width - ins.left - lColWidth - hgap - ins.right;
public void layoutContainer(Container parent) { LeftRightHeight lrh = calcSizes(parent); Dimension size = parent.getSize(); Insets ins = parent.getInsets(); int lColWidth = Math.min(size.width, lrh.left); int rColWidth = size.width - lColWidth - ins.left - ins.right; int height = Math.min(size.height, lrh.height); Dimension d; int lHeight = 0; int y = ins.top; for (int i = 0; i < parent.getComponentCount(); i++) { Component c = parent.getComponent(i); d = c.getPreferredSize(); if (i%2 == 0) { // left-hand column c.setBounds(ins.left, y, lColWidth, d.height); lHeight = d.height; } else { // right-hand column c.setBounds(lColWidth + ins.left + hgap, y, rColWidth, d.height); y += Math.max(d.height, lHeight) + vgap; } } }
c.setBounds(lColWidth + ins.left + hgap, y, rColWidth, d.height);
int width = c.getPreferredSize().width; if (c instanceof JTextField) { width = rColWidth; } c.setBounds(lColWidth + ins.left + hgap, y, width, d.height);
public void layoutContainer(Container parent) { LeftRightHeight lrh = calcSizes(parent); Dimension size = parent.getSize(); Insets ins = parent.getInsets(); int lColWidth = Math.min(size.width, lrh.left); int rColWidth = size.width - lColWidth - ins.left - ins.right; int height = Math.min(size.height, lrh.height); Dimension d; int lHeight = 0; int y = ins.top; for (int i = 0; i < parent.getComponentCount(); i++) { Component c = parent.getComponent(i); d = c.getPreferredSize(); if (i%2 == 0) { // left-hand column c.setBounds(ins.left, y, lColWidth, d.height); lHeight = d.height; } else { // right-hand column c.setBounds(lColWidth + ins.left + hgap, y, rColWidth, d.height); y += Math.max(d.height, lHeight) + vgap; } } }
frame.dispose(); }
System.exit(0); }
public void windowClosing(WindowEvent e) { frame.dispose(); }
final JFrame frame = new JFrame( "Photo properties" ); PhotoInfoController ctrl = new PhotoInfoController(); PhotoInfoEditor editor = new PhotoInfoEditor( ctrl ); ctrl.setPhoto( photo ); frame.getContentPane().add( editor, BorderLayout.CENTER ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.dispose( ); } } ); frame.pack(); frame.setVisible( true );
if (propertyDlg == null ) { propertyDlg = new PhotoInfoDlg( frame, true, photo ); } else { propertyDlg.setPhoto( photo ); } propertyDlg.showDialog();
public void showSelectionPropsDialog() { PhotoInfo photo = getSelected(); if ( photo != null ) { // TODO: Change PhotoInfoEditor to a dialog!!! final JFrame frame = new JFrame( "Photo properties" ); PhotoInfoController ctrl = new PhotoInfoController(); PhotoInfoEditor editor = new PhotoInfoEditor( ctrl ); ctrl.setPhoto( photo ); frame.getContentPane().add( editor, BorderLayout.CENTER ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.dispose( ); } } ); frame.pack(); frame.setVisible( true ); } }
(int) (0.0000001 + Math.log(theData.markerInfo.size()) / Math.log(10)) + 1;
(int) (0.0000001 + Math.log(Chromosome.size()) / Math.log(10)) + 1;
public Dimension getPreferredSize() { int wide = BORDER*2; int high = BORDER*2; if (filteredHaplos == null) {return new Dimension(wide, high);} // height for the marker digits int markerDigits = (int) (0.0000001 + Math.log(theData.markerInfo.size()) / Math.log(10)) + 1; high += MARKER_CHAR_WIDTH * markerDigits; // space for the diamond high += TAG_SPAN; int maxh = 0; for (int i = 0; i < filteredHaplos.length; i++){ maxh = Math.max(filteredHaplos[i].length, maxh); // size of genotypes for this column // +4 for the percentage reading wide += (filteredHaplos[i][0].getGeno().length + 4) * CHAR_WIDTH; // percentage plus the line size if (i != 0) wide += LINE_SPAN; } // +1 because of extra row for multi between the columns high += (maxh + 1) * ROW_HEIGHT; return new Dimension(wide, high); }
int markerCount = theData.markerInfo.size();
int markerCount = Chromosome.size();
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.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(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(); 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(); int markerCount = theData.markerInfo.size(); // 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; 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(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; 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) g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } //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(); for (int m = 0; m < 3; m++) { // 7*CHAR_WIDTH/2 = CHAR_WIDTH*3.5 to center it better // since the . char is right-aligned, and visually off 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); } //int multiX = x + totalWidth + 3; //g.drawString(nfMulti.format(multidprimeArray[i]), // multiX+2, windowY - 3); } left += LINE_SPAN; //x += (totalWidth + 40); //y = verticalOffset; //left = textRight + LINE_SPAN; } }
if (getColumns().isEmpty()) return; boolean donePk = false; int i = 0; Iterator it = getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) donePk = true; if (!donePk) { col.primaryKeySeq = new Integer(i); } else { col.primaryKeySeq = null; } i++; }
startCompoundEdit("Normalizing Primary Key"); if (getColumns().isEmpty()) return; boolean donePk = false; int i = 0; Iterator it = getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) donePk = true; Integer oldValue = col.getPrimaryKeySeq(); Integer newValue; if (!donePk) { newValue = new Integer(i); } else { newValue = null; } col.primaryKeySeq = newValue; col.fireDbObjectChanged("primaryKeySeq", oldValue, newValue); i++; }
public void normalizePrimaryKey() { try { if (getColumns().isEmpty()) return; boolean donePk = false; int i = 0; Iterator it = getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) donePk = true; if (!donePk) { col.primaryKeySeq = new Integer(i); } else { col.primaryKeySeq = null; } i++; } } catch (ArchitectException e) { logger.warn("Unexpected ArchitectException in normalizePrimaryKey "+e); } }
logger.warn("Unexpected ArchitectException in normalizePrimaryKey "+e);
logger.warn("Unexpected ArchitectException in normalizePrimaryKey "+e); } finally { endCompoundEdit("Normalizing Primary Key");
public void normalizePrimaryKey() { try { if (getColumns().isEmpty()) return; boolean donePk = false; int i = 0; Iterator it = getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) donePk = true; if (!donePk) { col.primaryKeySeq = new Integer(i); } else { col.primaryKeySeq = null; } i++; } } catch (ArchitectException e) { logger.warn("Unexpected ArchitectException in normalizePrimaryKey "+e); } }
getBody().run( context, output );
invokeBody(output);
public void doTag(XMLOutput output) throws Exception { if (select == null) { throw new MissingAttributeException( "select" ); } Object xpathContext = getXPathContext(); if ( select.booleanValueOf(xpathContext) ) { getBody().run( context, output ); } }
if (!(args[a].startsWith("-"))){ args[a] = "\"" + args[a] + "\""; }
public static void main(String[] args) { int exitValue = 0; //String dir = System.getProperty("user.dir"); //String ver = System.getProperty("java.version"); String sep = System.getProperty("file.separator"); String javaHome = System.getProperty("java.home"); //TODO:do some version checking and bitch at people with old JVMs /*StringTokenizer st = new StringTokenizer(ver, "."); while (st.hasMoreTokens()){ System.out.println(st.nextToken()); } */ //ugh windows sucks and we need to put quotes around path in case it contains spaces //on the other hand, linux seems displeased with the quoted classpath. sigh. String jarfile; if (System.getProperty("java.class.path").indexOf(" ") > 0 ){ jarfile = ("\""); jarfile += System.getProperty("java.class.path"); jarfile += "\""; }else{ jarfile = System.getProperty("java.class.path"); } String xmxArg = "512"; String argsToBePassed = ""; boolean headless = false; for (int a = 0; a < args.length; a++){ if (args[a].equalsIgnoreCase("-memory")){ a++; xmxArg = args[a]; }else{ argsToBePassed = argsToBePassed.concat(" " + args[a]); } if (args[a].equalsIgnoreCase("-n") || args[a].equalsIgnoreCase("-nogui")){ headless=true; } } try { //if the nogui flag is present we force it into headless mode String runString = javaHome + sep + "bin" + sep + "java -Dsun.java2d.noddraw=true -Xmx" + xmxArg + "m -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; while ( !dead && (line = besr.readLine()) != null) { if(line.lastIndexOf("Memory") != -1) { errorMsg.append(line); //if the child generated an "Out of Memory" error message, kill it child.destroy(); dead = true; }else { //for any other errors we show them to the user if(headless) { //if were in headless (command line) mode, then print the error text to command line System.err.println(line); } else { //otherwise print it to the error textarea if(errorTextArea == null) { //if this is the first error line then we need to create the JFrame with the //text area javax.swing.SwingUtilities.invokeAndWait(new Runnable() { public void run() { createAndShowGUI(); } }); } //if the user closed the contentFrame, then we want to reopen it when theres error text if(!contentFrame.isVisible()) { contentFrame.setVisible(true); } errorTextArea.append(line + "\n"); errorTextArea.setCaretPosition(errorTextArea.getDocument().getLength()); } } } final String realErrorMsg = errorMsg.toString(); //if the child died painfully throw up R.I.P. dialog if (dead){ if (headless){ System.err.println(errorMsg); }else{ Runnable showRip = new Runnable() { public void run() { JFrame jf = new JFrame(); JOptionPane.showMessageDialog(jf, realErrorMsg, null, JOptionPane.ERROR_MESSAGE);} }; SwingUtilities.invokeAndWait(showRip); } exitValue = -1; } } catch (Exception e) { if (headless){ System.err.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); }
Jimi.putImage("image/png", i, OutputFile.getName());
Jimi.putImage("image/png", i, OutputFile.getAbsolutePath());
private void processFile(String fileName, int fileType, String infoFileName){ try { HaploData textData; File OutputFile; File inputFile; AssociationTestSet customAssocSet; if(!quietMode && fileName != null){ System.out.println("Using data file: " + fileName); } inputFile = new File(fileName); if(!inputFile.exists()){ System.out.println("input file: " + fileName + " does not exist"); System.exit(1); } textData = new HaploData(); //Vector result = null; if(fileType == HAPS_FILE){ //read in haps file textData.prepareHapsInput(inputFile); } else if (fileType == PED_FILE) { //read in ped file textData.linkageToChrom(inputFile, PED_FILE); if(textData.getPedFile().isBogusParents()) { System.out.println("Error: One or more individuals in the file reference non-existent parents.\nThese references have been ignored."); } }else{ //read in hapmapfile textData.linkageToChrom(inputFile,HMP_FILE); } File infoFile = null; if (infoFileName != null){ infoFile = new File(infoFileName); } if (fileType != HAPS_FILE){ textData.prepareMarkerInput(infoFile,textData.getPedFile().getHMInfo()); }else{ textData.prepareMarkerInput(infoFile,null); } HashSet whiteListedCustomMarkers = new HashSet(); if (customAssocTestsFileName != null){ customAssocSet = new AssociationTestSet(customAssocTestsFileName); whiteListedCustomMarkers = customAssocSet.getWhitelist(); }else{ customAssocSet = null; } Hashtable snpsByName = new Hashtable(); for(int i=0;i<Chromosome.getUnfilteredSize();i++) { SNP snp = Chromosome.getUnfilteredMarker(i); snpsByName.put(snp.getName(), snp); } if(forceIncludeTags != null) { for(int i=0;i<forceIncludeTags.size();i++) { if(snpsByName.containsKey(forceIncludeTags.get(i))) { whiteListedCustomMarkers.add(snpsByName.get(forceIncludeTags.get(i))); } } } textData.setWhiteList(whiteListedCustomMarkers); boolean[] markerResults = new boolean[Chromosome.getUnfilteredSize()]; Vector result = null; if (fileType != HAPS_FILE){ result = textData.getPedFile().getResults(); //once check has been run we can filter the markers for (int i = 0; i < result.size(); i++){ if (((((MarkerResult)result.get(i)).getRating() > 0 || skipCheck) && Chromosome.getUnfilteredMarker(i).getDupStatus() != 2)){ markerResults[i] = true; }else{ markerResults[i] = false; } } }else{ //we haven't done the check (HAPS files) Arrays.fill(markerResults, true); } for (int i = 0; i < excludedMarkers.size(); i++){ int cur = ((Integer)excludedMarkers.elementAt(i)).intValue(); if (cur < 1 || cur > markerResults.length){ System.out.println("Excluded marker out of bounds: " + cur + "\nMarkers must be between 1 and N, where N is the total number of markers."); System.exit(1); }else{ markerResults[cur-1] = false; } } for(int i=0;i<Chromosome.getUnfilteredSize();i++) { if(textData.isWhiteListed(Chromosome.getUnfilteredMarker(i))) { markerResults[i] = true; } } Chromosome.doFilter(markerResults); if(!quietMode && infoFile != null){ System.out.println("Using marker information file: " + infoFile.getName()); } if(outputCheck && result != null){ CheckDataPanel cp = new CheckDataPanel(textData); cp.printTable(validateOutputFile(fileName + ".CHECK")); } Vector cust = new Vector(); AssociationTestSet blockTestSet = null; if(blockOutputType != -1){ textData.generateDPrimeTable(); Haplotype[][] haplos; Haplotype[][] filtHaplos; switch(blockOutputType){ case BLOX_GABRIEL: OutputFile = validateOutputFile(fileName + ".GABRIELblocks"); break; case BLOX_4GAM: OutputFile = validateOutputFile(fileName + ".4GAMblocks"); break; case BLOX_SPINE: OutputFile = validateOutputFile(fileName + ".SPINEblocks"); break; case BLOX_CUSTOM: OutputFile = validateOutputFile(fileName + ".CUSTblocks"); //read in the blocks file File blocksFile = new File(blockFileName); if(!quietMode) { System.out.println("Using custom blocks file " + blockFileName); } cust = textData.readBlocks(blocksFile); break; case BLOX_ALL: //handled below, so we don't do anything here OutputFile = null; break; default: OutputFile = validateOutputFile(fileName + ".GABRIELblocks"); break; } //this handles output type ALL if(blockOutputType == BLOX_ALL) { OutputFile = validateOutputFile(fileName + ".GABRIELblocks"); textData.guessBlocks(BLOX_GABRIEL); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile); }else if (!quietMode){ System.out.println("Skipping block output: no valid Gabriel blocks."); } OutputFile = validateOutputFile(fileName + ".4GAMblocks"); textData.guessBlocks(BLOX_4GAM); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile);; }else if (!quietMode){ System.out.println("Skipping block output: no valid 4 Gamete blocks."); } OutputFile = validateOutputFile(fileName + ".SPINEblocks"); textData.guessBlocks(BLOX_SPINE); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile); }else if (!quietMode){ System.out.println("Skipping block output: no valid LD Spine blocks."); } }else{ //guesses blocks based on output type determined above. textData.guessBlocks(blockOutputType, cust); haplos = textData.generateBlockHaplotypes(textData.blocks); if (haplos != null){ filtHaplos = filterHaplos(haplos); textData.pickTags(filtHaplos); textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), OutputFile); }else if (!quietMode){ System.out.println("Skipping block output: no valid blocks."); } } if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) { if (blockOutputType == BLOX_ALL){ System.out.println("Haplotype association results cannot be used with block output \"ALL\""); }else{ if (haplos != null){ blockTestSet = new AssociationTestSet(haplos,null); blockTestSet.saveHapsToText(validateOutputFile(fileName + ".HAPASSOC")); }else if (!quietMode){ System.out.println("Skipping block association output: no valid blocks."); } } } } if(outputDprime) { OutputFile = validateOutputFile(fileName + ".LD"); if (textData.dpTable != null){ textData.saveDprimeToText(OutputFile, TABLE_TYPE, 0, Chromosome.getSize()); }else{ textData.saveDprimeToText(OutputFile, LIVE_TYPE, 0, Chromosome.getSize()); } } if (outputPNG || outputCompressedPNG){ OutputFile = validateOutputFile(fileName + ".LD.PNG"); if (textData.dpTable == null){ textData.generateDPrimeTable(); textData.guessBlocks(BLOX_CUSTOM, new Vector()); } if (trackFileName != null){ textData.readAnalysisTrack(new File(trackFileName)); if(!quietMode) { System.out.println("Using analysis track file " + trackFileName); } } DPrimeDisplay dpd = new DPrimeDisplay(textData); BufferedImage i = dpd.export(0,Chromosome.getUnfilteredSize(),outputCompressedPNG); try{ Jimi.putImage("image/png", i, OutputFile.getName()); }catch(JimiException je){ System.out.println(je.getMessage()); } } AssociationTestSet markerTestSet =null; if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC){ markerTestSet = new AssociationTestSet(textData.getPedFile(),null,Chromosome.getAllMarkers()); markerTestSet.saveSNPsToText(validateOutputFile(fileName + ".ASSOC")); } if(customAssocSet != null) { if(!quietMode) { System.out.println("Using custom association test file " + customAssocTestsFileName); } try { customAssocSet.runFileTests(textData,markerTestSet.getMarkerAssociationResults()); customAssocSet.saveResultsToText(validateOutputFile(fileName + ".CUSTASSOC")); }catch(IOException ioe) { System.out.println("An error occured writing the custom association results file."); customAssocSet = null; } } if(doPermutationTest) { AssociationTestSet permTests = new AssociationTestSet(); permTests.cat(markerTestSet); permTests.cat(blockTestSet); final PermutationTestSet pts = new PermutationTestSet(permutationCount,textData.getPedFile(),customAssocSet,permTests); Thread permThread = new Thread(new Runnable() { public void run() { if (pts.isCustom()){ pts.doPermutations(PermutationTestSet.CUSTOM); }else{ pts.doPermutations(PermutationTestSet.SINGLE_PLUS_BLOCKS); } } }); permThread.start(); if(!quietMode) { System.out.println("Starting " + permutationCount + " permutation tests (each . printed represents 1% of tests completed)"); } int dotsPrinted =0; while(pts.getPermutationCount() - pts.getPermutationsPerformed() > 0) { while(( (double)pts.getPermutationsPerformed() / pts.getPermutationCount())*100 > dotsPrinted) { System.out.print("."); dotsPrinted++; } try{ Thread.sleep(100); }catch(InterruptedException ie) {} } System.out.println(); try { pts.writeResultsToFile(validateOutputFile(fileName + ".PERMUT")); } catch(IOException ioe) { System.out.println("An error occured while writing the permutation test results to file."); } } if(tagging != Tagger.NONE) { if(textData.dpTable == null) { textData.generateDPrimeTable(); } Vector snps = Chromosome.getAllMarkers(); HashSet names = new HashSet(); for (int i = 0; i < snps.size(); i++) { SNP snp = (SNP) snps.elementAt(i); names.add(snp.getName()); } HashSet filteredNames = new HashSet(); for(int i=0;i<Chromosome.getSize();i++) { filteredNames.add(Chromosome.getMarker(i).getName()); } Vector sitesToCapture = new Vector(); for(int i=0;i<Chromosome.getSize();i++) { sitesToCapture.add(Chromosome.getMarker(i)); } for (int i = 0; i < forceIncludeTags.size(); i++) { String s = (String) forceIncludeTags.elementAt(i); if(!names.contains(s)) { System.out.println("Marker " + s + " in the list of forced included tags does not appear in the marker info file."); System.exit(1); } } for (int i = 0; i < forceExcludeTags.size(); i++) { String s = (String) forceExcludeTags.elementAt(i); if(!names.contains(s)) { System.out.println("Marker " + s + " in the list of forced excluded tags does not appear in the marker info file."); System.exit(1); } } forceExcludeTags.retainAll(filteredNames); if(!quietMode) { System.out.println("Starting tagging."); } TaggerController tc = new TaggerController(textData,forceIncludeTags,forceExcludeTags,sitesToCapture, tagging); tc.runTagger(); while(!tc.isTaggingCompleted()) { try { Thread.sleep(100); }catch(InterruptedException ie) {} } tc.saveResultsToFile(validateOutputFile(fileName + ".TAGS")); tc.dumpTests(validateOutputFile(fileName + ".TESTS")); } } catch(IOException e){ System.err.println("An error has occured. This probably has to do with file input or output"); } catch(HaploViewException e){ System.err.println(e.getMessage()); } catch(PedFileException pfe) { System.err.println(pfe.getMessage()); } }
Object ret = call.invoke(new Object[]{getBodyText()});
Object answer = call.invoke(params);
public void doTag(XMLOutput output) throws Exception { if (endpoint == null) { throw new MissingAttributeException("endpoint"); } if (namespace == null) { throw new MissingAttributeException("namespace"); } if (method == null) { throw new MissingAttributeException("method"); } Service service = getService(); if (service == null) { service = createService(); } Call call = (Call) service.createCall(); // @todo Jelly should have native support for URL and QName // directly on properties call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName(new QName(namespace, method)); Object ret = call.invoke(new Object[]{getBodyText()}); if (var != null) { context.setVariable(var, ret); } else { // should turn the answer into XML events... throw new JellyException( "Not implemented yet; should stream results as XML events. Results: " + ret ); } }
context.setVariable(var, ret);
context.setVariable(var, answer);
public void doTag(XMLOutput output) throws Exception { if (endpoint == null) { throw new MissingAttributeException("endpoint"); } if (namespace == null) { throw new MissingAttributeException("namespace"); } if (method == null) { throw new MissingAttributeException("method"); } Service service = getService(); if (service == null) { service = createService(); } Call call = (Call) service.createCall(); // @todo Jelly should have native support for URL and QName // directly on properties call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName(new QName(namespace, method)); Object ret = call.invoke(new Object[]{getBodyText()}); if (var != null) { context.setVariable(var, ret); } else { // should turn the answer into XML events... throw new JellyException( "Not implemented yet; should stream results as XML events. Results: " + ret ); } }
throw new JellyException( "Not implemented yet; should stream results as XML events. Results: " + ret );
throw new JellyException( "Not implemented yet; should stream results as XML events. Results: " + answer );
public void doTag(XMLOutput output) throws Exception { if (endpoint == null) { throw new MissingAttributeException("endpoint"); } if (namespace == null) { throw new MissingAttributeException("namespace"); } if (method == null) { throw new MissingAttributeException("method"); } Service service = getService(); if (service == null) { service = createService(); } Call call = (Call) service.createCall(); // @todo Jelly should have native support for URL and QName // directly on properties call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName(new QName(namespace, method)); Object ret = call.invoke(new Object[]{getBodyText()}); if (var != null) { context.setVariable(var, ret); } else { // should turn the answer into XML events... throw new JellyException( "Not implemented yet; should stream results as XML events. Results: " + ret ); } }
JellyInterpreter interpreter = BeanShellExpressionFactory.getInterpreter(context);
JellyInterpreter interpreter = new JellyInterpreter(); interpreter.setJellyContext(context);
public Object evaluate(JellyContext context) { try { JellyInterpreter interpreter = BeanShellExpressionFactory.getInterpreter(context); if ( log.isDebugEnabled() ) { log.debug( "Evaluating EL: " + text ); } return interpreter.eval( text ); } catch (Exception e) { log.warn( "Caught exception evaluating: " + text + ". Reason: " + e, e ); return null; } }
log.debug( "Evaluating EL: " + text );
log.debug( "Evaluating beanshell: " + text );
public Object evaluate(JellyContext context) { try { JellyInterpreter interpreter = BeanShellExpressionFactory.getInterpreter(context); if ( log.isDebugEnabled() ) { log.debug( "Evaluating EL: " + text ); } return interpreter.eval( text ); } catch (Exception e) { log.warn( "Caught exception evaluating: " + text + ". Reason: " + e, e ); return null; } }
iis.close();
protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); log.debug( "Thumbnail loaded" ); txw.commit(); }
context.registerTagLibrary( "jelly:ant", new AntTagLibrary(project) );
context.registerTagLibrary( "jelly:ant", new AntTagLibrary() );
public JellyContext getJellyContext() throws MalformedURLException { if (context == null) { // take off the name off the URL String text = getUrl().toString(); int idx = text.lastIndexOf('/'); text = text.substring(0, idx + 1); JellyContext parentContext = new JellyContext(getRootContext(), new URL(text)); context = new AntJellyContext(project, parentContext); // register the Ant tag library context.registerTagLibrary( "jelly:ant", new AntTagLibrary(project) ); } return context; }
Class type = (Class) tags.get(name); Tag tag = (Tag) type.newInstance(); return TagScript.newInstance(tag);
Class type = (Class) tags.get(name); if ( type != null ) { Tag tag = (Tag) type.newInstance(); return TagScript.newInstance(tag); } return null;
public TagScript createTagScript(String name, Attributes attributes) throws Exception { Class type = (Class) tags.get(name); Tag tag = (Tag) type.newInstance(); return TagScript.newInstance(tag); }