PageRenderTime 53ms CodeModel.GetById 21ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 0ms

/src/tripod/tools/kinome/StepDataImport.java

https://bitbucket.org/caodac/kinome-viewer
Java | 288 lines | 239 code | 46 blank | 3 comment | 35 complexity | 87fe5e4ef33e19acab90276fdc004f7d MD5 | raw file
  1
  2package tripod.tools.kinome;
  3
  4import java.util.*;
  5import java.util.logging.Logger;
  6import java.util.logging.Level;
  7import java.io.*;
  8
  9import java.awt.*;
 10import java.awt.event.*;
 11import javax.swing.*;
 12import javax.swing.event.*;
 13import javax.swing.table.*;
 14
 15import org.pietschy.wizard.*;
 16import org.pietschy.wizard.models.*;
 17
 18import org.jdesktop.swingx.JXErrorPane;
 19
 20import com.jgoodies.forms.layout.*;
 21import com.jgoodies.forms.builder.PanelBuilder;
 22
 23import tripod.ui.kinome.*;
 24
 25
 26public class StepDataImport extends StepCommon 
 27    implements ActionListener, ListSelectionListener {
 28
 29    private static final Logger logger = Logger.getLogger
 30	(StepDataImport.class.getName());
 31
 32    public static final String NAME = "Data Import";
 33    public static final String DESC = 
 34	"Please setup your data file for import";
 35
 36    static class DataValueModel extends AbstractTableModel 
 37        implements Comparator {
 38
 39        String[] columns = new String[] {
 40            "Value",
 41            "Count"
 42        };
 43
 44        Class[] classes = new Class[] {
 45            Object.class,
 46            Integer.class
 47        };
 48
 49        Object[] rows;
 50        Map values;
 51        boolean isKinase;
 52
 53        DataValueModel () {
 54        }
 55
 56        void setValues (String name, Map values) {
 57            setValues (name, values, false);
 58        }
 59
 60        void setValues (String name, Map values, boolean isKinase) {
 61            this.values = values;
 62            this.isKinase = isKinase;
 63            columns[0] = name;
 64            rows = values.keySet().toArray(new Object[0]);
 65            Arrays.sort(rows, this);
 66            fireTableStructureChanged ();
 67        }
 68
 69        void clear () {
 70            values = null;
 71            rows = null;
 72            columns[0] = "Value";
 73            fireTableStructureChanged ();
 74        }
 75            
 76        public int compare (Object key1, Object key2) {
 77            Integer c1 = (Integer)values.get(key1);
 78            Integer c2 = (Integer)values.get(key2);
 79            if (c1 == null && c2 == null) return 0;
 80            if (c1 == null && c2 != null) return -1;
 81            if (c1 != null && c2 == null) return 1;
 82            return c2 - c1;
 83        }
 84
 85        public int getColumnCount () { 
 86            return isKinase ? (columns.length+1) : columns.length; 
 87        }
 88        public int getRowCount () { 
 89            return values != null ? values.size() : 0; 
 90        }
 91        public String getColumnName (int col) { 
 92            return col < columns.length ? columns[col] : "Kinase Gene?";
 93        }
 94        public Class getColumnClass (int col) { 
 95            return col < classes.length ? classes[col] : Boolean.class; 
 96        }
 97        public Object getValueAt (int row, int col) {
 98            if (col == 0) {
 99                return rows[row];
100            }
101            if (col < columns.length)
102                return values.get(rows[row]);
103
104            // is kinase?
105            return KinomeDataset.isValidKinase((String)rows[row]);
106        }
107    }
108
109
110    JCheckBox headerCb;
111    JTable table, viewtab;
112    String delimiter = "CSV";
113
114    public StepDataImport () {
115	super (NAME, DESC);
116    }
117
118    @Override
119    protected void initUI () {
120        JPanel pane = new JPanel (new BorderLayout (0, 2));
121        pane.add(createOptionPane (), BorderLayout.NORTH);
122
123        JSplitPane split = new JSplitPane (JSplitPane.VERTICAL_SPLIT);
124        split.setTopComponent(createTablePane ());
125        split.setBottomComponent(createViewPane ());
126        split.setDividerSize(5);
127        split.setResizeWeight(.5);
128        pane.add(split);
129
130        setLayout (new BorderLayout ());
131        add (pane);
132    }
133
134    Component createOptionPane () {
135        JPanel pane = new JPanel (new BorderLayout ());
136        pane.setBorder(BorderFactory.createCompoundBorder
137                       (BorderFactory.createTitledBorder(""),
138                        BorderFactory.createEmptyBorder(1,1,1,1)));
139        Box box = Box.createHorizontalBox();
140        box.add(headerCb = new JCheckBox ("Header"));
141        headerCb.setSelected(true);
142        headerCb.setToolTipText("Is the first line a header?");
143        box.add(Box.createHorizontalStrut(10));
144
145        Object[][] delimiters = new Object[][] {
146            {new JRadioButton ("CSV"), "Comma delimited file"},
147            {new JRadioButton ("Tab"), "Tab delimited file"},
148            {new JRadioButton ("Space"), "Space delimited file"}
149        };
150
151        ButtonGroup bg = new ButtonGroup ();
152        for (int i = 0; i < delimiters.length; ++i) {
153            box.add(Box.createHorizontalStrut(2));
154            AbstractButton ab = (AbstractButton)delimiters[i][0];
155            ab.addActionListener(this);
156            String text = (String)delimiters[i][1];
157            ab.setToolTipText(text);
158            box.add(ab);
159            bg.add(ab);
160            ab.setSelected(i == 0);
161        }
162        pane.add(box);
163
164        JButton btn = new JButton ("Load");
165        btn.setToolTipText("Load data file");
166        btn.addActionListener(this);
167        pane.add(btn, BorderLayout.EAST);
168
169        return pane;
170    }
171
172    Component createTablePane () {
173        JPanel pane = new JPanel (new BorderLayout ());
174        pane.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
175        pane.add(new JScrollPane (table = new JTable
176                                  (new DataImportModel ())));
177        table.getSelectionModel()
178            .setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
179        table.getSelectionModel().addListSelectionListener(this);
180
181        //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
182        table.setDefaultEditor
183            (DataLabel.class, new DefaultCellEditor 
184             (new JComboBox (EnumSet.allOf(DataLabel.class)
185                             .toArray(new DataLabel[0]))));
186        table.setDefaultEditor
187            (DataType.class, new DefaultCellEditor 
188             (new JComboBox (EnumSet.allOf(DataType.class)
189                             .toArray(new DataType[0]))));
190
191        return pane;
192    }
193
194    Component createViewPane () {
195        JPanel pane = new JPanel (new BorderLayout ());
196        pane.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
197        pane.add(new JScrollPane (viewtab = new JTable
198                                  (new DataValueModel ())));
199        return pane;
200    }
201
202    public void valueChanged (ListSelectionEvent e) {
203        if (e.getValueIsAdjusting()) return;
204        int row = table.getSelectedRow();
205        if (row >= 0) {
206            row = table.convertRowIndexToModel(row);
207            DataImportModel model = (DataImportModel)table.getModel();
208            DataLabel label = (DataLabel)model.getValueAt(row, 2);
209            Map values = model.getValues(row);
210            ((DataValueModel)viewtab.getModel()).setValues
211                ((String)model.getValueAt(row, 0), values, 
212                 label != null && label == DataLabel.Kinase);
213        }
214    }
215
216    public void actionPerformed (ActionEvent e) {
217	String cmd = e.getActionCommand();
218        if ("load".equalsIgnoreCase(cmd)) {
219            doLoad ();
220        }
221        else if (e.getSource() instanceof JRadioButton) {
222            delimiter = cmd;
223        }
224    }
225
226    protected void doLoad () {
227        JFileChooser chooser = getFileChooser ();
228        chooser.setDialogTitle("Please select input data file");
229        int op = chooser.showOpenDialog(this);
230        if (JFileChooser.APPROVE_OPTION == op) {
231            try {
232                File file = chooser.getSelectedFile();
233                loadData (file);
234                ((DataValueModel)viewtab.getModel()).clear();
235            }
236            catch (Exception ex) {
237                JXErrorPane.showDialog(ex);
238            }
239        }
240    }
241
242    protected void loadData (File file) throws IOException {
243        DataImportModel model = (DataImportModel)table.getModel();
244        String sep = "";
245        if ("csv".equalsIgnoreCase(delimiter)) 
246            sep = ",";
247        else if ("tab".equalsIgnoreCase(delimiter))
248            sep = "[\\t]";
249        else if ("space".equalsIgnoreCase(delimiter))
250            sep = "[\\s]";
251        else
252            throw new IllegalStateException
253                ("Unknown delimiter option: "+delimiter);
254
255        model.load(file, headerCb.isSelected(), sep);
256    }
257
258    @Override
259    public void applyState () throws InvalidStateException {
260        // make sure we have at least Kinase and Activity labels 
261        DataImportModel model = (DataImportModel)table.getModel();
262
263        EnumSet<DataLabel> labels = model.getLabels();
264        if (!labels.contains(DataLabel.Kinase))
265            throw new InvalidStateException 
266                ("At least one (and only one) column must be labeled Kinase!");
267        if (!labels.contains(DataLabel.Activity))
268            throw new InvalidStateException 
269                ("At least one (and only one) column must "
270                 +"be labeled Activity!");
271
272        getModel().put("DataImportModel", model);
273    }
274
275    public static void main (String[] argv) throws Exception {
276        SwingUtilities.invokeLater(new Runnable () {
277                public void run () {
278                    JFrame f = new JFrame ();
279                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
280                    StepDataImport ss = new StepDataImport ();
281                    f.getContentPane().add(ss);
282                    f.setSize(new Dimension (400, 400));
283                    f.pack();
284                    f.setVisible(true);
285                }
286            });
287    }
288}