View Javadoc
1   /*
2    * JBoss, Home of Professional Open Source
3    * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
4    * contributors by the @authors tag. See the copyright.txt in the
5    * distribution for a full listing of individual contributors.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * http://www.apache.org/licenses/LICENSE-2.0
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.jboss.as.quickstart.xml;
18  
19  import java.io.InputStream;
20  import java.text.ParseException;
21  import java.text.SimpleDateFormat;
22  import java.util.ArrayList;
23  import java.util.Date;
24  import java.util.Iterator;
25  import java.util.List;
26  
27  import javax.enterprise.context.RequestScoped;
28  import javax.enterprise.inject.Default;
29  import javax.inject.Inject;
30  
31  import org.dom4j.Document;
32  import org.dom4j.Element;
33  import org.dom4j.Node;
34  import org.dom4j.io.SAXReader;
35  import org.xml.sax.ErrorHandler;
36  import org.xml.sax.SAXException;
37  import org.xml.sax.SAXParseException;
38  
39  /**
40   * Implementation of parser based on DOM4J.
41   * 
42   * @author baranowb
43   * 
44   */
45  @RequestScoped
46  @Default
47  public class DOM4JXMLParser extends XMLParser {
48  
49      // Inject instance of error holder
50      @Inject
51      private Errors errorHolder;
52  
53      // Get the SAXReader object
54      private SAXReader dom4jReader = new SAXReader();
55      private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
56  
57      DOM4JXMLParser() throws Exception {
58          // Set SAX error handler. So errors atleast show up in console
59          this.dom4jReader.setErrorHandler(new ErrorHandler() {
60  
61              @Override
62              public void warning(SAXParseException e) throws SAXException {
63                  errorHolder.addErrorMessage("warning", e);
64              }
65  
66              @Override
67              public void fatalError(SAXParseException e) throws SAXException {
68                  errorHolder.addErrorMessage("fatal error", e);
69              }
70  
71              @Override
72              public void error(SAXParseException e) throws SAXException {
73                  errorHolder.addErrorMessage("error", e);
74              }
75          });
76  
77      }
78  
79      @Override
80      public List<Book> parseInternal(InputStream is) throws Exception {
81  
82          Document document = this.dom4jReader.read(is);
83  
84          List<Book> catalog = new ArrayList<Book>();
85          Element root = document.getRootElement();
86          if (!root.getQName().getName().equals("catalog")) {
87              throw new RuntimeException("Wrong element: " + root.getQName());
88          }
89  
90          Iterator<?> children = root.elementIterator();
91          while (children.hasNext()) {
92              Node n = (Node) children.next();
93              String childName = n.getName();
94              if (childName == null)
95                  continue;
96  
97              if (childName.equals("book")) {
98                  Book b = parseBook((Element) n);
99                  catalog.add(b);
100             }
101         }
102 
103         return catalog;
104 
105     }
106 
107     private Book parseBook(Element n) {
108         Book b = new Book();
109         Iterator<?> children = n.elementIterator();
110         /*
111          * parse book element, we have to once more iterate over children.
112          */
113         while (children.hasNext()) {
114             Node child = (Node) children.next();
115             String childName = child.getName();
116             // empty/text nodes dont have name
117             if (childName == null)
118                 continue;
119 
120             if (childName.equals("author")) {
121                 Element childElement = (Element) child;
122 
123                 String textVal = childElement.getTextTrim();
124                 b.setAuthor(textVal);
125             } else if (childName.equals("title")) {
126                 Element childElement = (Element) child;
127 
128                 String textVal = childElement.getTextTrim();
129                 b.setTitle(textVal);
130             } else if (childName.equals("genre")) {
131                 Element childElement = (Element) child;
132 
133                 String textVal = childElement.getTextTrim();
134                 b.setGenre(textVal);
135             } else if (childName.equals("price")) {
136                 Element childElement = (Element) child;
137 
138                 String textVal = childElement.getTextTrim();
139                 b.setPrice(Float.parseFloat(textVal));
140             } else if (childName.equals("publish_date")) {
141                 Element childElement = (Element) child;
142 
143                 String textVal = childElement.getTextTrim();
144                 Date d;
145                 try {
146 
147                     d = DATE_FORMATTER.parse(textVal);
148                     b.setPublishDate(d);
149                 } catch (ParseException e) {
150                     throw new RuntimeException(e);
151                 }
152 
153             } else if (childName.equals("description")) {
154                 Element childElement = (Element) child;
155                 String textVal = childElement.getTextTrim();
156                 b.setDescription(textVal);
157             }
158 
159         }
160 
161         return b;
162     }
163 }