View Javadoc

1   /**
2    * Copyright 2009 Timothy Johnston Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
3    * file except in compliance with the License. You may obtain a copy of the License at
4    * 
5    * http://www.apache.org/licenses/LICENSE-2.0
6    * 
7    * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
8    * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
9    * specific language governing permissions and limitations under the License.
10   */
11  
12  package com.timjohnstondev.unitconverter.logic;
13  
14  import java.io.IOException;
15  import java.io.InputStream;
16  import java.util.logging.Logger;
17  import javax.xml.parsers.ParserConfigurationException;
18  import javax.xml.parsers.SAXParser;
19  import javax.xml.parsers.SAXParserFactory;
20  import org.xml.sax.SAXException;
21  import org.xml.sax.helpers.DefaultHandler;
22  
23  /**
24   * Parser that parses a XML file, but the important part is the {@link ConversionFactorParserHandler}. The XML file is
25   * defined in this class and should probably allow to select different data source.
26   */
27  public class ConversionFactorParser
28  {
29    private static Logger logger = Logger.getLogger(ConversionFactorParser.class.getName());
30    private final String dataFileName = "/com/timjohnstondev/unitconverter/model/ConversionFactors.xml";
31    private DefaultHandler handler;
32    private SAXParser saxParser;
33  
34    /**
35     * Constructs and initializes a {@code ConversionFactorParser} to the given DefaultHandler.
36     * 
37     * @param newHandler the parser handler that defines how the XML file elements are handled.
38     */
39    public ConversionFactorParser(final DefaultHandler newHandler)
40    {
41      handler = newHandler;
42      create();
43    }
44  
45    /**
46     * Connects to the XML file and parses it.
47     */
48    public final void parse()
49    {
50      try
51      {
52        final InputStream dataFileStream = getClass().getResourceAsStream(dataFileName);
53        saxParser.parse(dataFileStream, handler);
54      }
55      catch (SAXException e)
56      {
57        logger.severe(e.getMessage());
58      }
59      catch (IOException e)
60      {
61        logger.severe(e.getMessage());
62      }
63    }
64  
65    private void create()
66    {
67      final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
68      try
69      {
70        saxParser = parserFactory.newSAXParser();
71      }
72      catch (SAXException e)
73      {
74        logger.severe(e.getMessage());
75      }
76      catch (ParserConfigurationException e)
77      {
78        logger.severe(e.getMessage());
79      }
80    }
81  }