001    /*
002     * 
003     * $Revision: 13085 $ $Date: 2008-02-06 18:27:24 +0100 (Mi, 06 Feb 2008) $
004     *
005     * This file is part of ***  M y C o R e  ***
006     * See http://www.mycore.de/ for details.
007     *
008     * This program is free software; you can use it, redistribute it
009     * and / or modify it under the terms of the GNU General Public License
010     * (GPL) as published by the Free Software Foundation; either version 2
011     * of the License or (at your option) any later version.
012     *
013     * This program is distributed in the hope that it will be useful, but
014     * WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     * GNU General Public License for more details.
017     *
018     * You should have received a copy of the GNU General Public License
019     * along with this program, in a file called gpl.txt or license.txt.
020     * If not, write to the Free Software Foundation Inc.,
021     * 59 Temple Place - Suite 330, Boston, MA  02111-1307 USA
022     */
023    
024    package org.mycore.services.fieldquery;
025    
026    import java.io.File;
027    import java.io.IOException;
028    import java.io.InputStream;
029    import java.util.ArrayList;
030    
031    import javax.xml.transform.Transformer;
032    import javax.xml.transform.TransformerFactory;
033    import javax.xml.transform.stream.StreamResult;
034    import javax.xml.transform.stream.StreamSource;
035    
036    import org.apache.log4j.Logger;
037    import org.jdom.Document;
038    import org.jdom.JDOMException;
039    import org.jdom.input.SAXBuilder;
040    import org.jdom.transform.JDOMSource;
041    import org.mycore.common.MCRConfigurationException;
042    import org.mycore.frontend.cli.MCRCommand;
043    import org.mycore.frontend.cli.MCRExternalCommandInterface;
044    import org.mycore.parsers.bool.MCRCondition;
045    
046    /**
047     * Provides commands to test the query classes using the command line interface
048     * 
049     * @author Frank Lützenkirchen
050     * @author Arne Seifert
051     * @author Jens Kupferschmidt
052     * @version $Revision: 13085 $ $Date: 2008-02-06 18:27:24 +0100 (Mi, 06 Feb 2008) $
053     */
054    public class MCRQueryCommands implements MCRExternalCommandInterface {
055    
056        /**
057         * The method returns all available commands.
058         * 
059         * @return an ArrayList of MCRCommands
060         */
061        public ArrayList<MCRCommand> getPossibleCommands() {
062            ArrayList<MCRCommand> commands = new ArrayList<MCRCommand>();
063            commands.add(new MCRCommand("run query from file {0}", "org.mycore.services.fieldquery.MCRQueryCommands.runQueryFromFile String", "Runs a query that is specified as XML in the given file"));
064            commands.add(new MCRCommand("run local query {0}", "org.mycore.services.fieldquery.MCRQueryCommands.runLocalQueryFromString String", "Runs a query specified as String on the local host"));
065            commands.add(new MCRCommand("run distributed query {0}", "org.mycore.services.fieldquery.MCRQueryCommands.runAllQueryFromString String", "Runs a query specified as String on the local host and all remote hosts"));
066            return commands;
067        }
068    
069        /**
070         * Runs a query that is specified as XML in the given file. The results are
071         * written to stdout. To transform the result data it use the stylesheet
072         * results-commandlinequery.xsl.
073         * 
074         * @param filename
075         *            the name of the XML file with the query condition
076         */
077        public static void runQueryFromFile(String filename) throws JDOMException, IOException {
078            File file = new File(filename);
079            if (!file.exists()) {
080                String msg = "File containing XML query does not exist: " + filename;
081                throw new org.mycore.common.MCRUsageException(msg);
082            }
083            if (!file.canRead()) {
084                String msg = "File containing XML query not readable: " + filename;
085                throw new org.mycore.common.MCRUsageException(msg);
086            }
087    
088            Document xml = new SAXBuilder().build(new File(filename));
089            MCRQuery query = MCRQuery.parseXML(xml);
090            MCRResults results = MCRQueryManager.search(query);
091            buildOutput(results);
092        }
093    
094        /**
095         * Runs a query that is specified as String against the local host. The
096         * results are written to stdout.
097         * 
098         * @param querystring
099         *            the string with the query condition
100         */
101        public static void runLocalQueryFromString(String querystring) {
102            MCRCondition cond = (new MCRQueryParser()).parse(querystring);
103            MCRQuery query = new MCRQuery(cond);
104            MCRResults results = MCRQueryManager.search(query);
105            buildOutput(results);
106        }
107    
108        /**
109         * Runs a query that is specified as String against all hosts. The
110         * results are written to stdout.
111         * 
112         * @param querystring
113         *            the string with the query condition
114         */
115        public static void runAllQueryFromString(String querystring) {
116            MCRCondition cond = (new MCRQueryParser()).parse(querystring);
117            MCRQuery query = new MCRQuery(cond);
118            query.setHosts( MCRQueryClient.ALL_HOSTS );
119            MCRResults results = MCRQueryManager.search(query);
120            buildOutput(results);
121        }
122    
123        /** Transform the results to an output using stylesheets */
124        private final static void buildOutput(MCRResults results) {
125            // read stylesheet
126            String xslfile = "results-commandlinequery.xsl";
127            InputStream in = MCRQueryCommands.class.getResourceAsStream("/" + xslfile);
128            if (in == null) {
129                throw new MCRConfigurationException("Can't read stylesheet file " + xslfile);
130            }
131    
132            // transform data
133            try {
134                StreamSource source = new StreamSource(in);
135                TransformerFactory transfakt = TransformerFactory.newInstance();
136                Transformer trans = transfakt.newTransformer(source);
137                StreamResult sr = new StreamResult(System.out);
138                trans.transform(new JDOMSource((new org.jdom.Document(results.buildXML()))), sr);
139            } catch (Exception ex) {
140                Logger LOGGER = Logger.getLogger(MCRQueryCommands.class);
141                LOGGER.error("Error while tranforming query result XML using XSLT");
142                LOGGER.debug(ex.getMessage());
143                LOGGER.info("Stop.");
144                LOGGER.info("");
145                return;
146            }
147        }
148    }