001    // GraphLab Project: http://graphlab.sharif.edu
002    // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology
003    // Distributed under the terms of the GNU General Public License (GPL): http://www.gnu.org/licenses/
004    package graphlab.plugins.main.saveload;
005    
006    
007    import graphlab.graph.graph.GraphModel;
008    import graphlab.plugins.main.saveload.core.GraphIOException;
009    import graphlab.plugins.main.saveload.core.extension.GraphReaderExtension;
010    import graphlab.plugins.main.saveload.xmlparser.GraphmlHandlerImpl;
011    import graphlab.plugins.main.saveload.xmlparser.GraphmlParser;
012    import org.xml.sax.InputSource;
013    import org.xml.sax.SAXException;
014    
015    import javax.xml.parsers.ParserConfigurationException;
016    import java.io.File;
017    import java.io.FileInputStream;
018    import java.io.IOException;
019    
020    public class Load implements GraphReaderExtension {
021    
022        /**
023         * loads a graph from a file, note that this method clears the graph first
024         *
025         * @param selectedFile
026         * @param g
027         */
028        public static GraphModel loadGraphFromFile(File selectedFile) throws IOException, ParserConfigurationException, SAXException {
029            FileInputStream istream = new FileInputStream(selectedFile);
030            GraphmlHandlerImpl ghi = new GraphmlHandlerImpl();
031    
032            GraphmlParser.parse(new InputSource(istream), ghi);
033            istream.close();
034            return ghi.getGraph();
035        }
036    
037        public boolean accepts(File file) {
038            return SaveLoadPluginMethods.getExtension(file).equals(getExtension());
039        }
040    
041        public String getName() {
042            return "GraphML";
043        }
044    
045        public String getExtension() {
046            return "xml";
047        }
048    
049        public GraphModel read(File file) throws GraphIOException {
050            try {
051                return loadGraphFromFile(file);
052            } catch (Exception e) {
053                e.printStackTrace();
054                throw new GraphIOException(e.getMessage());
055            }
056        }
057    
058        public String getDescription() {
059            return "GraphML Standard File Format for Graphs (Load)";
060        }
061    }
062