001    /*
002     * CRIMSON
003     * Copyright (c) 2006, Stephen Fisher, Susan Davidson, and Junhyong Kim, 
004     * University of Pennsylvania.
005     *
006     * This program is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU General Public License as
008     * published by the Free Software Foundation; either version 2 of the
009     * License, or (at your option) any later version.
010     *
011     * This program is distributed in the hope that it will be useful, but
012     * WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * General Public License for more details.
015     *
016     * You should have received a copy of the GNU General Public License
017     * along with this program; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019     * 02110-1301 USA.
020     *
021     * @(#)FileIO.java
022     */
023    
024    package edu.upenn.crimson.io;
025    
026    import edu.upenn.crimson.*;
027    import java.util.Iterator;
028    import java.util.TreeSet;
029    import java.util.Collection;
030    import java.io.*;
031    
032    /**
033     * Import and export utilities.
034     *
035     * @author  Stephen Fisher
036     * @version $Id: FileIO.java,v 1.22 2009/07/16 16:19:52 fisher Exp $
037     */
038    
039    public class FileIO {
040    
041        //--------------------------------------------------------------------------
042        // Miscellaneous Methods
043    
044            /*
045             * Load python file containing commands without function
046             * definitions. 
047             */
048            public static void loadPython(String filename) {
049                    if (CrimsonUtils.isEmpty(filename)) return;
050                    
051                    File file = new File(filename);
052                    // if the file does not exist then exit
053                    if (! file.exists()) {
054                                    CrimsonUtils.printError("File '" + filename + "' does not exists.");
055                                    return;
056                    }
057                    
058                    try {
059                                    FileReader fReader = new FileReader(file);
060                                    BufferedReader bReader = new BufferedReader(fReader);
061    
062                                    String line;
063                                    while ((line = bReader.readLine()) != null) CrimsonMain.console.exec(line);
064                                            
065                                    bReader.close();
066                                    fReader.close();
067                    } catch (FileNotFoundException e) { // problem with FileOutputStream
068                                    CrimsonUtils.printError("File '" + filename + "' can not be opened.");
069                                    CrimsonUtils.printError(e.getMessage());
070                                    return;
071                    } catch (IOException e) { // problem with ObjectOutputStream.  
072                                    // XXX do we need to close bReader()?
073                                    CrimsonUtils.printError("Error reading input file '" + filename + "'.");
074                                    CrimsonUtils.printError(e.getMessage());
075                                    return;
076                    }
077            }
078    
079            /** 
080            * Write string to file. If append is true then the string will be
081            * appended to the end of the file. Nothing will be done if an
082            * empty string is provided.
083            */
084            public static void writeString(String filename, boolean append, String out) {
085                    // can't use isEmpty() because that will ignore a string "\n"
086                    if ((out == null) || (out.length() == 0)) return;
087    
088                    if (! CrimsonUtils.isEmpty(filename)) {
089                            File file = new File(filename);
090                            try {
091                                    FileWriter fWriter = new FileWriter(file, append);
092                                    BufferedWriter bWriter = new BufferedWriter(fWriter);
093                                    
094                                    bWriter.write(out);
095                                    
096                                    bWriter.flush();
097                                    bWriter.close();
098                                    fWriter.close();
099                            } catch (FileNotFoundException e) { // problem with FileOutputStream
100                                    CrimsonUtils.printError("File '" + filename + "' can not be opened.");
101                                    CrimsonUtils.printError(e.getMessage());
102                                    return;
103                            } catch (IOException e) { // problem with ObjectOutputStream.  
104                                    // XXX do we need to close bWriter()?
105                                    CrimsonUtils.printError("Error writting output file '" + filename + "'.");
106                                    CrimsonUtils.printError(e.getMessage());
107                                    return;
108                            }
109                    }
110            }
111    
112            /** 
113            * Export the Query to a file based on it's ID.  This will
114            * overwrite any existing file.  
115            */
116            public static String exportQuery(String id) {
117                    return exportQuery(id, id, true);
118            }
119    
120            /** 
121            * Export the Query to a python file.  This will append ".py" to
122            * the filename, if necessary.  The python file created can be
123            * imported into jython to re-create the query object.  If no
124            * filename is given, then the output will be returned as a
125            * string.
126            */
127            public static String exportQuery(String id, String filename, boolean overwrite) {
128                    if (CrimsonUtils.isEmpty(id)) return "";
129    
130                    Query query = ObjectHandles.getQuery(id);
131                    if (query == null) {
132                                    CrimsonUtils.printError("Unable to export unknown query: " + id);
133                                    return "";
134                    }
135    
136                    String out = "";
137                    out += "_query = Query('" + query.getTreeID() + "', '" + query.getID() + "')\n";
138                    out += "_query.setNotes('" + query.getNotes() + "')\n";
139                    out += "_query.setLeafSelection(" + query.getLeafSelection() + ")\n";
140                    out += "_query.setNumLeaves(" + query.getNumLeaves() + ")\n";
141                    out += "_query.setTempDepthThresh(" + query.getTempDepthThresh() + ")\n";
142                    out += "_query.setLevelThresh(" + query.getLevelThresh() + ")\n";
143                    out += "_query.setSequenceSelection(" + query.getSequenceSelection() + ")\n";
144                    out += "_query.setNumPositions(" + query.getNumPositions() + ")\n";
145                    out += "_query.setSeed(" + query.getSeed() + ")\n";
146                    for (Iterator i = query.getLeaves().iterator(); i.hasNext();)
147                                    out += "_query.addLeaf('" + (String) i.next() + "')\n";
148                    for (Iterator i = query.getPartitions().iterator(); i.hasNext();)
149                                    out += "_query.addPartition('" + (String) i.next() + "')\n";
150                    for (Iterator i = query.getPositions().iterator(); i.hasNext();)
151                                    out += "_query.addPosition('" + (String) i.next() + "')\n";
152                    
153                    if (CrimsonUtils.isEmpty(filename)) {
154                                    return out;
155                    } else {
156                                    if (! filename.endsWith(".py")) filename += ".py";
157    
158                                    File file = new File(filename);
159                                    // if the file already exists and not supposed to
160                                    // overwrite it, then return on error.
161                                    if (file.exists() && (! overwrite)) {
162                                            CrimsonUtils.printError("File '" + filename + "' already exists.");
163                                            return "";
164                                    }
165    
166                                    try {
167                                            FileWriter fWriter = new FileWriter(file);
168                                            BufferedWriter bWriter = new BufferedWriter(fWriter);
169    
170                                            bWriter.write(out);
171                                            //                                      bWriter.newLine();
172                                            
173                                            bWriter.flush();
174                                            bWriter.close();
175                                            fWriter.close();
176                                    } catch (FileNotFoundException e) { // problem with FileOutputStream
177                                            CrimsonUtils.printError("File '" + filename + "' can not be opened.");
178                                            CrimsonUtils.printError(e.getMessage());
179                                            return "";
180                                    } catch (IOException e) { // problem with ObjectOutputStream.  
181                                            // XXX do we need to close bWriter()?
182                                            CrimsonUtils.printError("Error writting output file '" + filename + "'.");
183                                            CrimsonUtils.printError(e.getMessage());
184                                            return "";
185                                    }
186    
187                                    return "";
188                    }
189            }
190    
191            /** 
192            * This will print the list of species to the output file
193            * ('species.list'), one species ID per line.  If 'onlyLeaves' is
194            * true then the output file will be 'leaf.list' and only leaves
195            * will be included.
196            */
197            public static void printSpecies(Collection species, boolean onlyLeaves) {
198                    if ((species == null) || (species.size() == 0)) return;
199    
200                    try {
201                                    FileWriter fWriter;
202                                    if (onlyLeaves) fWriter = new FileWriter(new File("leaf.list"));
203                                    else fWriter = new FileWriter(new File("species.list"));
204                                    BufferedWriter bWriter = new BufferedWriter(fWriter);
205    
206                                    for (Iterator i = species.iterator(); i.hasNext();)  {
207                                            Species curSpecies = (Species) i.next();
208                                            if (onlyLeaves) {
209                                                    if (curSpecies.isLeaf()) bWriter.write(curSpecies.getID() + "\n");
210                                            } else {
211                                                    bWriter.write(curSpecies.getID() + "\n");
212                                            }
213                                            // bWriter.newLine();
214                                    }
215    
216                                    bWriter.flush();
217                                    bWriter.close();
218                                    fWriter.close();
219                    } catch (FileNotFoundException e) { // problem with FileOutputStream
220                                    if (onlyLeaves) CrimsonUtils.printError("File 'leaf.list' can not be opened.");
221                                    else CrimsonUtils.printError("File 'species.list' can not be opened.");
222                                    CrimsonUtils.printError(e.getMessage());
223                                    return;
224                    } catch (IOException e) { // problem with ObjectOutputStream.  
225                                    // XXX do we need to close bWriter()?
226                                    if (onlyLeaves) CrimsonUtils.printError("Error writting output file 'leaf.list'.");
227                                    else CrimsonUtils.printError("Error writting output file 'species.list'.");
228                                    CrimsonUtils.printError(e.getMessage());
229                                    return;
230                    }
231            }
232    
233            /** 
234            * This will print the list of leaves to the output file
235            * ('leaf.list'), one leaf ID per line.
236            */
237            /*
238            public static void printLeaves(TreeSet leaves) {
239                    if ((leaves == null) || (leaves.size() == 0)) return;
240    
241                    try {
242                                    FileWriter fWriter = new FileWriter(new File("leaf.list"));
243                                    BufferedWriter bWriter = new BufferedWriter(fWriter);
244    
245                                    for (Iterator i = leaves.iterator(); i.hasNext();)  {
246                                            bWriter.write(((Species) i.next()).getID() + "\n");
247                                            // bWriter.newLine();
248                                    }
249    
250                                    bWriter.flush();
251                                    bWriter.close();
252                                    fWriter.close();
253                    } catch (FileNotFoundException e) { // problem with FileOutputStream
254                                    CrimsonUtils.printError("File 'leaf.list' can not be opened.");
255                                    CrimsonUtils.printError(e.getMessage());
256                                    return;
257                    } catch (IOException e) { // problem with ObjectOutputStream.  
258                                    // XXX do we need to close bWriter()?
259                                    CrimsonUtils.printError("Error writting output file 'leaf.list'.");
260                                    CrimsonUtils.printError(e.getMessage());
261                                    return;
262                    }
263            }
264            */
265    
266            /** 
267            * This will print the list of positions to the output file
268            * ('positions.list'), one position per line.  Note that the
269            * position values in the file go from 1 to N, not from 0 to N-1.
270            * This routine requires a TreeSet because we want the positions
271            * sorted for testing.
272            */
273            public static void printPositions(TreeSet positions) {
274                    if ((positions == null) || (positions.size() == 0)) return;
275    
276                    try {
277                                    FileWriter fWriter = new FileWriter(new File("position.list"));
278                                    BufferedWriter bWriter = new BufferedWriter(fWriter);
279    
280                                    for (Iterator i = positions.iterator(); i.hasNext();) {
281                                            bWriter.write(((Integer) i.next()) + "\n");
282                                    }
283    
284                                    bWriter.flush();
285                                    bWriter.close();
286                                    fWriter.close();
287                    } catch (FileNotFoundException e) { // problem with FileOutputStream
288                                    CrimsonUtils.printError("File 'position.list' can not be opened.");
289                                    CrimsonUtils.printError(e.getMessage());
290                                    return;
291                    } catch (IOException e) { // problem with ObjectOutputStream.  
292                                    // XXX do we need to close bWriter()?
293                                    CrimsonUtils.printError("Error writting output file 'position.list'.");
294                                    CrimsonUtils.printError(e.getMessage());
295                                    return;
296                    }
297            }
298    
299    } // FileIO.java