View Javadoc
1   /*
2    * The MIT License
3    * Copyright © 2004-2014 Fabrizio Giustina
4    * Copyright © 2022-2022 Web-Legacy
5    *
6    * Permission is hereby granted, free of charge, to any person obtaining a copy
7    * of this software and associated documentation files (the "Software"), to deal
8    * in the Software without restriction, including without limitation the rights
9    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10   * copies of the Software, and to permit persons to whom the Software is
11   * furnished to do so, subject to the following conditions:
12   *
13   * The above copyright notice and this permission notice shall be included in
14   * all copies or substantial portions of the Software.
15   *
16   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22   * THE SOFTWARE.
23   */
24  package net.sf.maventaglib.util;
25  
26  import java.io.BufferedInputStream;
27  import java.io.BufferedOutputStream;
28  import java.io.CharArrayReader;
29  import java.io.File;
30  import java.io.FileInputStream;
31  import java.io.FileNotFoundException;
32  import java.io.FileOutputStream;
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.OutputStream;
36  
37  import javax.xml.parsers.DocumentBuilder;
38  import javax.xml.parsers.DocumentBuilderFactory;
39  import javax.xml.parsers.FactoryConfigurationError;
40  import javax.xml.parsers.ParserConfigurationException;
41  import javax.xml.parsers.SAXParserFactory;
42  import javax.xml.transform.Source;
43  import javax.xml.transform.Transformer;
44  import javax.xml.transform.TransformerException;
45  import javax.xml.transform.TransformerFactory;
46  import javax.xml.transform.sax.SAXSource;
47  import javax.xml.transform.stream.StreamResult;
48  import javax.xml.transform.stream.StreamSource;
49  
50  import org.apache.maven.plugin.MojoExecutionException;
51  import org.w3c.dom.DOMException;
52  import org.w3c.dom.Node;
53  import org.w3c.dom.NodeList;
54  import org.xml.sax.EntityResolver;
55  import org.xml.sax.InputSource;
56  import org.xml.sax.XMLReader;
57  
58  /**
59   * @author fgiust
60   * @version $Revision: 217 $ ($Author: fgiust $)
61   */
62  public class XmlHelper
63  {
64  
65      /**
66       * Returns a DocumentBuilder instance.
67       *
68       * @return DocumentBuilder instance
69       *
70       * @throws MojoExecutionException in case of an XML-Parser-Error
71       */
72      public static DocumentBuilder getDocumentBuilder()
73          throws MojoExecutionException
74      {
75          DocumentBuilder builder;
76          DocumentBuilderFactory factory;
77          try
78          {
79              builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
80              factory = DocumentBuilderFactory.newInstance();
81              factory.setValidating( false );
82              factory.setNamespaceAware( false );
83              factory.setExpandEntityReferences( false );
84              builder.setEntityResolver( new EntityResolver()
85              {
86  
87                  public InputSource resolveEntity( String publicId, String systemId )
88                  {
89                      return new InputSource( new CharArrayReader( new char[0] ) );
90                  }
91              } );
92  
93              return builder;
94          }
95          catch ( FactoryConfigurationError | ParserConfigurationException e )
96          {
97              throw new MojoExecutionException( "Unable to obtain a new xml parser", e );
98          }
99  
100     }
101 
102     /**
103      * Returns a XMLReader instance.
104      *
105      * @return XMLReader instance
106      *
107      * @throws MojoExecutionException in case of an SAX-Parser-Error
108      */
109     protected static XMLReader getReader()
110         throws MojoExecutionException
111     {
112         try
113         {
114             SAXParserFactory factory = SAXParserFactory.newInstance();
115             factory.setNamespaceAware( true );
116             factory.setValidating( false );
117             XMLReader reader = factory.newSAXParser().getXMLReader();
118 
119             reader.setEntityResolver( new EntityResolver()
120             {
121 
122                 public InputSource resolveEntity( String publicId, String systemId )
123                 {
124                     return new InputSource( new CharArrayReader( new char[0] ) );
125                 }
126             } );
127             return reader;
128         }
129         catch ( FactoryConfigurationError | Exception e )
130         {
131             throw new MojoExecutionException( "Unable to obtain a new xml parser", e );
132         }
133 
134     }
135 
136     /**
137      * Apply an xsl stylesheet to a java.xml.tranform.Source.
138      *
139      * @param src Source
140      * @param stylesheet xslt used for transformation
141      * @param outputFile output file
142      *
143      * @throws MojoExecutionException xml parsing/transforming exceptions
144      * @throws TransformerException If an unrecoverable error occurs
145      *   during the course of the transformation.
146      * @throws IOException if output directory could not created
147      */
148     protected static void applyXslt( Source src, String stylesheet, File outputFile )
149         throws MojoExecutionException, TransformerException, IOException
150     {
151         OutputStream fos = null;
152         File outputDir = outputFile.getParentFile();
153         if (!(outputDir.mkdirs() || outputDir.isDirectory())) {
154             throw new IOException("Unable to create output directory " + outputDir.getAbsolutePath());
155         }
156 
157         try
158         {
159             try
160             {
161                 fos = new BufferedOutputStream( new FileOutputStream( outputFile ) );
162             }
163             catch ( FileNotFoundException e )
164             {
165                 throw new MojoExecutionException(
166                                                   "Unable to complete xslt transformation. Unable to create output file "
167                                                       + outputFile.getAbsolutePath() + ": " + e.getMessage(), e );
168             }
169 
170             // result
171             StreamResult res = new StreamResult( fos );
172 
173             // transformer
174             InputStream xsl = XmlHelper.class.getResourceAsStream( stylesheet );
175             if ( xsl == null )
176             {
177                 throw new MojoExecutionException( "Can't find stylesheet " + stylesheet );
178             }
179 
180             Transformer transformer = TransformerFactory.newInstance().newTransformer( new StreamSource( xsl ) );
181             transformer.transform( src, res );
182 
183         }
184         finally
185         {
186             try
187             {
188                 if ( fos != null )
189                 {
190                     fos.close();
191                 }
192             }
193             catch ( IOException ignored )
194             {
195                 // ignore
196             }
197         }
198     }
199 
200     /**
201      * Transform a file using the given xsl stylesheet.
202      * @param inputFile input file
203      * @param stylesheet xslt used for transformation
204      * @param outputFile output file
205      * @throws MojoExecutionException xml parsing/transforming exceptions
206      */
207     protected static void applyXslt( File inputFile, String stylesheet, File outputFile )
208         throws MojoExecutionException
209     {
210 
211         InputStream fis = null;
212         try
213         {
214             fis = new BufferedInputStream( new FileInputStream( inputFile ) );
215             XMLReader reader = getReader();
216             Source src = new SAXSource( reader, new InputSource( fis ) );
217             applyXslt( src, stylesheet, outputFile );
218         }
219         catch ( Exception e )
220         {
221             throw new MojoExecutionException( "Unable to complete xslt transformation from "
222                 + inputFile.getAbsolutePath() + " to " + outputFile.getAbsolutePath() + " using " + stylesheet + ": "
223                 + e.getMessage(), e );
224         }
225         finally
226         {
227             try
228             {
229                 if ( fis != null )
230                 {
231                     fis.close();
232                 }
233             }
234             catch ( IOException ignored )
235             {
236                 // ignore
237             }
238         }
239     }
240 
241     /**
242      * Get Node text content.
243      * @param baseNode The node.
244      * @return The text content of the node.
245      * @throws org.w3c.dom.DOMException Any DOM exceptions.
246      */
247     public static String getTextContent( Node baseNode )
248         throws DOMException
249     {
250 
251         StringBuffer buf = new StringBuffer();
252 
253         NodeList nodeList = baseNode.getChildNodes();
254 
255         for ( int j = 0; j < nodeList.getLength(); j++ )
256         {
257             Node k = nodeList.item( j );
258             buf.append( k.getNodeValue() );
259             //getTextContent( k );
260         }
261 
262         return buf.toString();
263     }
264 
265 }