001    /*
002     * Copyright 2010-2013 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.jet.cli.common.modules;
018    
019    import com.intellij.openapi.util.Pair;
020    import com.intellij.openapi.util.io.StreamUtil;
021    import com.intellij.util.SmartList;
022    import org.jetbrains.annotations.NotNull;
023    import org.jetbrains.jet.cli.common.messages.*;
024    import org.xml.sax.Attributes;
025    import org.xml.sax.SAXException;
026    import org.xml.sax.helpers.DefaultHandler;
027    
028    import javax.xml.parsers.ParserConfigurationException;
029    import javax.xml.parsers.SAXParser;
030    import javax.xml.parsers.SAXParserFactory;
031    import java.io.*;
032    import java.util.Collections;
033    import java.util.List;
034    
035    import static org.jetbrains.jet.cli.common.messages.CompilerMessageLocation.*;
036    import static org.jetbrains.jet.cli.common.messages.CompilerMessageSeverity.*;
037    
038    public class ModuleXmlParser {
039    
040        public static final String MODULES = "modules";
041        public static final String MODULE = "module";
042        public static final String NAME = "name";
043        public static final String OUTPUT_DIR = "outputDir";
044        public static final String INCREMENTAL_CACHE = "incrementalCache";
045        public static final String SOURCES = "sources";
046        public static final String PATH = "path";
047        public static final String CLASSPATH = "classpath";
048        public static final String EXTERNAL_ANNOTATIONS = "externalAnnotations";
049    
050        @NotNull
051        public static Pair<List<ModuleDescription>, String> parseModuleDescriptionsAndIncrementalCacheDir(
052                @NotNull String xmlFile,
053                @NotNull MessageCollector messageCollector
054        ) {
055            FileInputStream stream = null;
056            try {
057                stream = new FileInputStream(xmlFile);
058                //noinspection IOResourceOpenedButNotSafelyClosed
059                return new ModuleXmlParser(messageCollector).parse(new BufferedInputStream(stream));
060            }
061            catch (FileNotFoundException e) {
062                MessageCollectorUtil.reportException(messageCollector, e);
063                return Pair.create(Collections.<ModuleDescription>emptyList(), null);
064            }
065            finally {
066                StreamUtil.closeStream(stream);
067            }
068        }
069    
070        private final MessageCollector messageCollector;
071        private String incrementalCacheDir;
072        private final List<ModuleDescription> descriptions = new SmartList<ModuleDescription>();
073        private DefaultHandler currentState;
074    
075        private ModuleXmlParser(@NotNull MessageCollector messageCollector) {
076            this.messageCollector = messageCollector;
077        }
078    
079        private void setCurrentState(@NotNull DefaultHandler currentState) {
080            this.currentState = currentState;
081        }
082    
083        private Pair<List<ModuleDescription>, String> parse(@NotNull InputStream xml) {
084            try {
085                setCurrentState(initial);
086                SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
087                saxParser.parse(xml, new DelegatedSaxHandler() {
088                    @NotNull
089                    @Override
090                    protected DefaultHandler getDelegate() {
091                        return currentState;
092                    }
093                });
094                return Pair.create(descriptions, incrementalCacheDir);
095            }
096            catch (ParserConfigurationException e) {
097                MessageCollectorUtil.reportException(messageCollector, e);
098            }
099            catch (SAXException e) {
100                messageCollector.report(ERROR, MessageRenderer.PLAIN.renderException(e), NO_LOCATION);
101            }
102            catch (IOException e) {
103                MessageCollectorUtil.reportException(messageCollector, e);
104            }
105            return Pair.create(Collections.<ModuleDescription>emptyList(), null);
106        }
107    
108        private final DefaultHandler initial = new DefaultHandler() {
109            @Override
110            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
111                if (!MODULES.equalsIgnoreCase(qName)) {
112                    throw createError(qName);
113                }
114    
115                incrementalCacheDir = attributes.getValue(INCREMENTAL_CACHE);
116                setCurrentState(insideModules);
117            }
118        };
119    
120        private final DefaultHandler insideModules = new DefaultHandler() {
121            @Override
122            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
123                if (!MODULE.equalsIgnoreCase(qName)) {
124                    throw createError(qName);
125                }
126    
127                setCurrentState(new InsideModule(
128                        getAttribute(attributes, NAME, qName),
129                        getAttribute(attributes, OUTPUT_DIR, qName)
130                ));
131            }
132    
133            @Override
134            public void endElement(String uri, String localName, String qName) throws SAXException {
135                if (MODULE.equalsIgnoreCase(qName) || MODULES.equalsIgnoreCase(qName)) {
136                    setCurrentState(insideModules);
137                }
138            }
139        };
140    
141        private class InsideModule extends DefaultHandler {
142    
143            private final ModuleDescription.Impl moduleDescription;
144            private InsideModule(String name, String outputDir) {
145                this.moduleDescription = new ModuleDescription.Impl();
146                this.moduleDescription.setName(name);
147                this.moduleDescription.setOutputDir(outputDir);
148                descriptions.add(moduleDescription);
149            }
150    
151            @Override
152            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
153                if (SOURCES.equalsIgnoreCase(qName)) {
154                    String path = getAttribute(attributes, PATH, qName);
155                    moduleDescription.addSourcePath(path);
156                }
157                else if (CLASSPATH.equalsIgnoreCase(qName)) {
158                    String path = getAttribute(attributes, PATH, qName);
159                    moduleDescription.addClassPath(path);
160                }
161                else if (EXTERNAL_ANNOTATIONS.equalsIgnoreCase(qName)) {
162                    String path = getAttribute(attributes, PATH, qName);
163                    moduleDescription.addAnnotationPath(path);
164                }
165                else {
166                    throw createError(qName);
167                }
168            }
169    
170            @Override
171            public void endElement(String uri, String localName, String qName) throws SAXException {
172                if (MODULE.equalsIgnoreCase(qName)) {
173                    setCurrentState(insideModules);
174                }
175            }
176        }
177    
178        @NotNull
179        private static String getAttribute(Attributes attributes, String qName, String tag) throws SAXException {
180            String name = attributes.getValue(qName);
181            if (name == null) {
182                throw new SAXException("No '" + qName + "' attribute for " + tag);
183            }
184            return name;
185        }
186    
187        private static SAXException createError(String qName) throws SAXException {
188            return new SAXException("Unexpected tag: " + qName);
189        }
190    }